解码Json文件结果空白页

问题描述 投票:0回答:1

我试图用PHP解码下面的JSON文件内容。

"notification": {/* code related to notification */ },
"HOME_SCREEN": 
    {
        "Phone": 
        {
            "position": 1 ,                         
            "list": 
            [
                {
                    "position": 1,
                    "productID": "105"

                }
            ]
        },
    },
"notify": { /* code related to notify */},  

我跟着链接herehere并尝试如下。但它给空白页....

$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

php json
1个回答
1
投票

您可以/应该对解码JSON文件做更多的事情。

正如在php documentation for json_decode中所写,您使用的是$assoc = true,因此您将整个JSON文件转换为关联数组。如果要将JSON文件解码为OBJECT或ASSOCIATIVE ARRAY,则由您决定。直到这一点,你说得对。

为了您的理解,主要区别在于:

  • ARRAY,您可以使用$json['notification']访问值
  • OBJECT,您使用$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'];
}
© www.soinside.com 2019 - 2024. All rights reserved.