doushupu2521 2010-12-06 09:47
浏览 91

while循环和数组的问题

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);



while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
   $result['recipe']=$recipe;

$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);

 while($ingredient = mysql_fetch_assoc($result2)){


        $result['ingredient'] = $ingredient;

 }

 echo json_encode($result);
}

this code show me all the recipes but only the last ingredients i.e

{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},
"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},
"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}

i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.

  • 写回答

2条回答 默认 最新

  • donglao7947 2010-12-06 09:49
    关注
    $result['ingredient'] = $ingredient;
    

    Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:

    $result['ingredient'][] = $ingredient;
    

    To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:

    while($ingredient = mysql_fetch_assoc($result2)){
            $result['ingredient'][] = $ingredient;
    
    
    }
    
    print_r($result['ingredient']);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答