我试图用PHP解码下面的JSON文件内容。
"notification": {/* code related to notification */ },
"HOME_SCREEN":
{
"Phone":
{
"position": 1 ,
"list":
[
{
"position": 1,
"productID": "105"
}
]
},
},
"notify": { /* code related to notify */},
我跟着链接here和here并尝试如下。但它给空白页....
$string = file_get_contents("test.json");
$json_a = json_decode($string, true);
foreach ($json_a as $Phone => $person_a)
{
echo isset($person_a['position']);
}
也试过:
$json_string = file_get_contents("test.json");
$decoded = json_decode($json_string);
$comments = $decoded->data[0]->comments->data;
foreach($comments as $comment){
$position = $comment->position;
echo $comment['position'];
}
及以下:
$url = 'http://url.com/test.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json as $i){
echo $i['position'];
}
编辑
检查Json file在线,其有效的json,相同的json文件在更好的视图:https://pastebin.com/mUEpqfaM
您可以/应该对解码JSON文件做更多的事情。
正如在php documentation for json_decode中所写,您使用的是$assoc = true
,因此您将整个JSON文件转换为关联数组。如果要将JSON文件解码为OBJECT或ASSOCIATIVE ARRAY,则由您决定。直到这一点,你说得对。
为了您的理解,主要区别在于:
$json['notification']
访问值$json->notification
访问值我更喜欢ARRAY,因为我更容易导航并使用foreach
循环。如评论中所述,您应该检查已解码文件的结构,以便了解如何访问您感兴趣的值。
这样做的最小代码是
$string = file_get_contents("test.json");
$json = json_decode($string, true);
echo "<pre>";
print_r($json);
echo "</pre>";
假设您想要访问$ json数组中HOME_SCREEN / Phone>列表中的位置,为此,您需要使用此foreach
循环:
foreach ($json['HOME_SCREEN']['Phone']['list'] as $item) {
echo $item['position'];
}