2012-01-27 40 views
2

從來就得到如下:JSON致命錯誤的foreach

include('php/get_recipe_byID.php'); 
$jsonstring1 = $recipe_byidarr; 
$recip = json_decode($recipe_byidarr, true); 

print_r($recip); 

foreach ($recip['Data']['Recipes'] as $key => $newrecipe) { 
     // echo '<li> 
     //   <a href="/recipe_search.php?id=' . $recipe['ID'] . '">'; 
     echo 'seas'; 
     echo $newrecipe['TITLE']; 
     echo '<br><br>';   
} 

當我把它在瀏覽器中,它告訴我,

Fatal error: Cannot use string offset as an array in /var/www/recipe_search.php on line 43 

這是foreach循環線。

$ RECIP如下:

{"Data":{"Recipes":{"Recipe_9":{"ID":"9","TITLE":"Schnitzel","TEXT":"Alex\u00b4s Hausmannskost","COUNT_PERSONS":"4","DURATION":"40","USER_ID":"1","DATE":"2011-09-16 00:00:00"}}},"Message":null,"Code":200} 

不要任何人知道我的錯誤是什麼?

+0

看來,既然你PHP5需要顯式聲明$ RECIP爲使用json_decode之前的數組。在json_decode之前添加'$ recip = array();'行。只是我在Google上看到的一個建議:) – 2012-01-27 11:13:34

+0

我已經嘗試過了,沒有幫助 – user896692 2012-01-27 11:19:37

回答

1

試試看:

$taskSeries = $array['Data']['Recipes']['Recipe_'.$_GET['id']]; 
if(array_key_exists('TITLE', $taskSeries)) { 
    $taskSeries = array($taskSeries); 
} 
foreach($taskSeries as $task) { 
    $title = $task['TITLE']; 
    // do something with $title and other 
} 
+0

問題是,身份證可能會有所不同......它並不總是_9 ... – user896692 2012-01-27 11:19:27

+0

所以你的意思是它可以是任何id而不是_9,或者它會像_1,_2,_3 ...等等? – 2012-01-27 11:21:42

+0

爲什麼不呢?用'foreach($ recip ['Data'] ['Recipes'] ['Recipe_'。$ _GET ['id']]作爲$ key => $ newrecipe){ echo $ newrecipe ['TITLE']; }' 但我仍然有同樣的錯誤! – user896692 2012-01-27 11:33:28