2016-08-02 199 views
0

我需要打印通过下面的json数据循环的每个值。通过Json循环的foreach循环

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

我想的是:

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

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

回答

0

您不需要->{$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) 

然后它只是普通object iteration

可以如果您想从解码对象中获取单个特定属性,尽管括号不是必需的,但可以使用该语法。

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

您已经混乱了你的foreach一点。将其更改为:

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