Reputation: 303
I know it's been asked many times and I've gone through a good 15 - 20 questions trying to figure out how to get it to work.
JSON
{"menu": {
"title":"Title One",
"link":"Link One",
"title":"Title Two",
"link":"Link Two"}
}
PHP
$string = file_get_contents("test.json");
$json_a = json_decode($string,true);
foreach($json_a['menu'] as $key => $value) {
echo $key . ": " . $value . "<br />";
}
This so far only displays
title: Title Two
link: Link Two
as opposed to
title: Title One
link: Link One
title: Title Two
link: Link Two
Also am I correct in thinking $json_a[menu]
does not need apostrophes because $json_a
is not a function? it works with or without.
Thanks in advance.
Upvotes: -1
Views: 646
Reputation: 817238
You can't have multiple entries with the same key in an array. While JSON might allow it, when it's parsed by PHP, the last definition of the key,value pair wins.
It looks like menu
should be an array of objects instead:
{
"menu": [{
"title":"Title One",
"link":"Link One"
}, {
"title":"Title Two",
"link":"Link Two"
}]
}
PHP
foreach($json_a['menu'] as $value) {
echo $value['title'] . ": " . $value['link'] . "<br />";
}
Upvotes: 2