Loop json array in php -
i know it's been asked many times , i've gone through 15 - 20 questions trying figure out how 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'] $key => $value) { echo $key . ": " . $value . "<br />"; }
this far displays
title: title 2 link: link 2
as opposed to
title: title 1 link: link 1 title: title 2 link: link 2
also correct in thinking $json_a[menu]
not need apostrophes because $json_a
not function? works or without.
thanks in advance.
you can't have multiple entries same key in array. while json might allow it, when it's parsed php, last definition of key,value pair wins.
it looks menu
should array of objects instead:
{ "menu": [{ "title":"title one", "link":"link one" }, { "title":"title two", "link":"link two" }] }
php
foreach($json_a['menu'] $value) { echo $value['title'] . ": " . $value['link'] . "<br />"; }
Comments
Post a Comment