JSON致命错误foreach

时间:2012-01-27 09:59:25

标签: php html foreach json

我有以下内容:

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}

有人知道我的错误在哪里吗?

1 个答案:

答案 0 :(得分: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
}