我需要打印通过以下json数据循环的每个值。
{
"Name": "xyz",
"Address": "abc",
"City": "London",
"Phone": "123456"
}
我尝试的是:
$DecodedFile = json_decode(file_get_contents("file.json"));
foreach ($DecodedFile->{$key} as $value) {
echo "$value <br>";
}
您不需要->{$key}
。只是:
foreach ($DecodedFile as $value) {
echo "$value <br>";
}
或者如果你也想使用密钥:
foreach ($DecodedFile as $key => $value) {
echo "$key: $value <br>";
}
在你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)
然后它只是常规的对象迭代。
如果您想从解码对象中获得单个特定属性,则可以使用该语法,尽管括号不是必需的。
$key = 'City';
echo $DecodedFile->$key;
你的前臂有点乱。更改为:
foreach($DecodedFile as $key=>$value)