-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

Muhammad Rauuf
  • 108
  • 1
  • 14

1 Answers1

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'];
}
Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50