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

Popular posts from this blog

c# - Unity IoC Lifetime per HttpRequest for UserStore -

Change the color of an oval at click in Java AWT -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -