Imaulle Posted June 6, 2011 Share Posted June 6, 2011 Hello, I'm stuck trying to parse a json file with the following code. Before I had $json = json_decode($string,true) and it partially worked, but it would not print all of the info, only the first 'Name001' and nothing else. When I remove that line I get a warning saying invalid argument supplied for foreach().. It's my understanding if I use the json_decode then I don't have an object anymore? I think I want an object correct? $json = file_get_contents('file.json'); foreach($json as $key => $val) { echo $key; if (gettype($val) == "object") { foreach ($val as $key => $val) { echo "$key => $val\n"; } } } { "Name001" : { "ID" : "001", "description" : "bleh", "ZipLocation" : "something1.zip" }, "Name002" : { "ID" : "002", "description" : "bleh", "ZipLocation" : "something2.zip" } } Any ideas?? thanks!!!! Link to comment https://forums.phpfreaks.com/topic/238527-parsing-json-with-php/ Share on other sites More sharing options...
kenrbnsn Posted June 6, 2011 Share Posted June 6, 2011 You're overwriting the $key & $val in your second foreach loop, they need to be different variables than your outer loop: <?php $json = '{ "Name001" : { "ID" : "001", "description" : "bleh", "ZipLocation" : "something1.zip" }, "Name002" : { "ID" : "002", "description" : "bleh", "ZipLocation" : "something2.zip" } }'; $json_ary = json_decode($json,true); foreach($json_ary as $key => $val) { echo "$key<br>\n"; foreach ($val as $key2 => $val2) { echo "... $key2 => $val2<br>\n"; } } ?> Ken Link to comment https://forums.phpfreaks.com/topic/238527-parsing-json-with-php/#findComment-1225741 Share on other sites More sharing options...
Imaulle Posted June 6, 2011 Author Share Posted June 6, 2011 ahhhh! silly me! thank you Link to comment https://forums.phpfreaks.com/topic/238527-parsing-json-with-php/#findComment-1225743 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.