2016-08-04 59 views
0

我的PHP代碼工作正常時,返回的結果是這樣 - >如何驗證PHP中的JSON空對象

{ 
"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" 
} 
] 
} 

,但我得到錯誤

(注意:未定義的變量:finaltrailers中...)

當結果返回像這一點 - >

{ 
"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

您必須定義變量才能在trim中使用它。 只需在代碼的開頭添加它即可。

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

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

wow thx man :)解答(y) –