简体   繁体   中英

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>";
}

You've jumbled up your foreach a little. Change it to this:

foreach($DecodedFile as $key=>$value)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM