while循环和数组的问题

时间:2010-12-06 09:47:29

标签: php

$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);
}

这段代码向我展示了所有食谱,但只展示了最后的成分,即

{"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"}}

我想输出与食谱ID 14相关的所有成分记录,这只是打印最后一种成分。

2 个答案:

答案 0 :(得分:2)

$result['ingredient'] = $ingredient;

每次使用最新的$result['ingredient']值替换变量$ingredient,最后返回的值应该是:

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

为每个$result['ingredient']$ingredient数组中增加/创建新值。然后,您可以根据需要输出此数组。使用print_r($result['ingredient'])会向您展示其内容......为了自己试一试:

while($ingredient = mysql_fetch_assoc($result2)){
        $result['ingredient'][] = $ingredient;


}

print_r($result['ingredient']);

答案 1 :(得分:0)

如果我理解你想要做什么,有一种方法可以通过使用JOIN在一个查询中获取配方和成分来大量优化代码:

$recipes = array();
$recipe_ingredients = array();

$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";

$resouter = mysql_query($query, $conn);

$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";

while( $recipe = mysql_fetch_array($resouter) )
{

  if( $buffer_rec_id != $result['recipe.rec_id'] )
  {
      $recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);

      $recipe_ingredients = array(  );

      $buffer_rec_id = $result['recipe.rec_id'];
      $buffer_rec_name = $result['recipe.rec_name'];
      $buffer_rec_cat = $result['recipe.rec_category'];
  }
  else
  {
      $recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );

  }

}

$print_r($recipes);

此代码应该为您提供一个多维数组,您可以稍后使用它来获取所需的数据。

我让您调整代码以获得您需要的信息。