2011-12-07 166 views
1

我試圖通過使用foreach()的JSON字符串進行循環。不過,我不斷收到以下錯誤:通過JSON字符串循環訪問

"Notice: Trying to get property of non-object". 

奇怪的是,當我複製並粘貼JSON字符串,然後運行foreach(),它做工精細。只是爲了提供一些細節,我正在使用Best-Buy API。

既然這似乎對每個人都適用here是否有可能是最佳購買給我的數據有問題?

請幫忙,我已經嘗試了一切!

UPDATE抱歉沒有發佈代碼。這裏是:

$info = json_decode($test, true); 
function tagGen($info){ 
foreach($info as $key => $value){ 
} 
+0

一個代碼示例將是非常有用的,因爲我們不知道你是否有一個錯字或更深層次的問題。無論如何,我會刺探答案... – MikeMurko

回答

0

您可能沒有在JSON字符串上使用json_decode。看看我會如何做到這一點:

$json = "somejsonstring"; 
$json_array = json_decode($json, true); 

foreach($json_array as $element) { 
    echo $element['some key']; 
} 

請注意給予json_decode方法的「真正的」第二個參數。這返回一個關聯數組而不是標準的PHP對象。在foreach循環中使用起來更容易。

希望有所幫助,雖然你的問題應該包括一個代碼示例。

+0

感謝您的快速回復。我正在使用json_decode,這是直接從程序中獲取的。我正在撕掉我的頭髮。 $ test = curl_exec($ curl_object); \t curl_close($ curl_object); \t $ info = json_decode($ test,true); –

1

由於您還沒有發佈代碼,所以我們可以認爲你有一個字符串傑森編碼。我親愛的json編碼的字符串是某種JavaScript形式的東西。而foreach是一個php循環。所以,如果你有一個json編碼的字符串,你想在foreach循環中使用它,你必須使用json_decode函數。

當您將應用json_decode你將有一個字符串從documentation

Returns the value encoded in json in appropriate PHP type.

Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively.

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

對於一些示例代碼。

$str=json_decode($yourjson); 
foreach($str as $key=>$value) 
{} 
+0

看來只要Json在一個變量中就會出現這個錯誤。當我把它作爲字符串通過我的foreach()時,在執行print_r之後它工作正常。 –