首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环和数组问题

while循环和数组问题
EN

Stack Overflow用户
提问于 2010-12-06 17:47:29
回答 2查看 154关注 0票数 0
代码语言:javascript
复制
$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);
}

这段代码显示了所有食谱,但只显示了最后的配料,即

代码语言:javascript
复制
{"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相关的所有配料记录,这只是打印最后一种配料。

EN

回答 2

Stack Overflow用户

发布于 2010-12-06 17:49:54

代码语言:javascript
复制
$result['ingredient'] = $ingredient;

每次将变量$result['ingredient']替换为最新的$ingredient值,并以最后返回的值结束,则应使用:

代码语言:javascript
复制
$result['ingredient'][] = $ingredient;

为每个$ingredient$result['ingredient']数组中增加一个/创建一个新值。然后,您可以根据需要输出此数组。使用print_r($result['ingredient'])将向您显示其content...to,请自己查看尝试:

代码语言:javascript
复制
while($ingredient = mysql_fetch_assoc($result2)){
        $result['ingredient'][] = $ingredient;


}

print_r($result['ingredient']);
票数 2
EN

Stack Overflow用户

发布于 2010-12-06 18:08:52

如果我正确理解了您想要做的事情,那么有一种方法可以对代码进行大量优化,方法是使用连接在单个查询中获取食谱和配料:

代码语言:javascript
复制
$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);

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

我让您修改代码以获得所需的信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4365059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档