2012-01-27 93 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