-1

I have a json data from API and i want to insert them to my database table. I have extract $data using json_encode function, but when i tried to access data inside $myJson with some of this code, it gives me an error result.

$data = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';
$myJson = json_decode($data);

foreach ($myJson as $mj){
    echo $mj['math_score'];
    // echo $mj->math_score; <= error
    // echo $mj[0]->post->math_score; <= error
    // echo $mj->post->math_score; <= error
}

The error : Invalid argument supplied for foreach().

sorry for my bad grammar, any answer will be greatly appreciated. Thanks

2
  • 1
    json_decode() Commented Dec 20, 2016 at 7:12
  • It give me error "Object of class stdClass could not be converted to string" Commented Dec 20, 2016 at 7:13

1 Answer 1

1

There is built in php function json_decode()

Try

$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';

$json = json_decode($json);

echo $json->posts{0}->post->math_score;

By default json_decode return object. If you want an array then you need to pass second argument true to json_decode.

Try it with Array

$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';

$json = json_decode($json, true);

foreach ($json['posts'] as $mj)
{
    echo $mj['post']['math_score'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works, Thanks Hassaan

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.