Jump to content

parsing json with php


Imaulle

Recommended Posts

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

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

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.