如何在php中验证json空对象

时间:2016-08-04 12:14:10

标签: php arrays json validation foreach

我的php代码在返回结果时工作正常 - >

{
"id": 267935,
"results": [
{
"key": "rc94yWXcyr0",
"name": "Trailer 1",
"site": "YouTube"
},
{  
"key": "GZ0Bey4YUGI",
"name": "Official Trailer",
"site": "YouTube"
},
{
"key": "y1fZg0hhBX8",
"name": "Official Trailer 2",
"site": "YouTube"
}
]
}

但我得到错误

  

(注意:未定义的变量:...中的最终定位器)

结果返回时如 this - >

{
"id": 392344,
"results": [

]
}

这是我的 php代码 - >

  $trailer = $json2['results'];
    foreach($trailer as $trailers=>$keytrailers){
                       foreach($keytrailers as $alltrailers=>$allkeytrailers){
                           if($alltrailers == 'key'){
                           @ $finaltrailers .=  $allkeytrailers.',';
                           }
                       }
                   }
echo trim($finaltrailers,",");

我如何验证空数组并给出错误我自己?请帮帮我谢谢。

1 个答案:

答案 0 :(得分:1)

您必须定义变量才能在trim中使用它。 只需在代码的开头添加它即可。

$finaltrailers = '';
$trailer = $json2['results'];

foreach($trailer as $trailers=>$keytrailers){
    foreach($keytrailers as $alltrailers=>$allkeytrailers){
        if($alltrailers == 'key'){
             @ $finaltrailers .=  $allkeytrailers.',';
        }
     }
}
echo trim($finaltrailers,",");