Salil Lambay Salil Lambay - 4 months ago 9
PHP Question

foreach loop for looping through Json

I need to print each value looping through the below json data.

{
"Name": "xyz",
"Address": "abc",
"City": "London",
"Phone": "123456"
}


What I tried is:

$DecodedFile = json_decode(file_get_contents("file.json"));

foreach ($DecodedFile->{$key} as $value) {
echo "$value <br>";
}

Answer

You don't need the ->{$key}. It's just:

foreach ($DecodedFile as $value) {
    echo "$value <br>";
}

or if you want to use the key as well:

foreach ($DecodedFile as $key => $value) {
    echo "$key: $value <br>";
}

After you json_decode, you get this $DecodedFile:

object(stdClass)[1]
  public 'Name' => string 'xyz' (length=3)
  public 'Address' => string 'abc' (length=3)
  public 'City' => string 'London' (length=6)
  public 'Phone' => string '123456' (length=6)

And then it's just regular object iteration.

You can use that syntax if you want to get a single specific property from the decoded object, although the brackets aren't necessary.

$key = 'City';
echo $DecodedFile->$key;
Comments