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
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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.