简体   繁体   English

通过Json循环的foreach循环

[英]foreach loop for looping through Json

I need to print each value looping through the below json data. 我需要打印通过以下json数据循环的每个值。

{
    "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} . 您不需要->{$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 : json_decode ,您将获得以下$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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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