php - 具有关联数组的 PHP foreach 函数的正确语法

标签 php arrays foreach associative-array

我在 PHP 中有以下名为 $ingredient_difference 的数组(下面的示例输出):

Array (
  [total_remaining_ingredients] => Array (
    [0] => 2 [1] => 3 [2] => 10
  )
  [idrecipe] => Array (
    [0] => 8 [1] => 10 [2] => 9
  )
  [value] => Array ( [0] => 1 [1] => 1 [2] => 1 )
) 

我尝试使用“foreach”至少提取 idrecipe 的值,但使用以下代码得到 undefined index :

foreach($ingredient_difference as $recipe_output)
{
    echo $recipe_output['idrecipe']."<br />";
}

我知道上面的方法并不完全正确,但这也不起作用(“idrecipe”、“value”和“total_remaining_ingredients”的未定义索引错误):

foreach($ingredient_difference as $c => $rowkey)
{
    $sorted_idrecipe[] = $rowkey['idrecipe'];
    $sorted_value[] = $rowkey['value'];
    $sorted_remaining_ingredients[] = $rowkey['total_remaining_ingredients']; 
}

我的 foreach 语法中缺少什么?或者有更好的办法吗?

这个 foreach 构造也会给出 undefined index 错误:

foreach($ingredient_difference as $rowkey => $index_value)
{
    $id_value[$key] = $index_value['idrecipe'];
    $value_value[$key] = $index_value['value'];
    $tri_value[$key] = $index_value['total_remaining_ingredients'];
}

感谢 ComFreek 的回答:

$result_ingredient_difference = array();
$count_id = count($ingredient_difference['idrecipe']);

for ($i=0; $i<$count_id; $i++)
{
  $result_ingredient_difference[] = array(
  'tri' => $ingredient_difference['total_remaining_ingredients'][$i],
  'idrecipe' => $ingredient_difference['idrecipe'][$i],
  'value' => $ingredient_difference['value'][$i]
  );
}
//rearranged array of $result_ingredient_difference able to call proper indexing with the below
foreach($result_ingredient_difference as $rowkey => $index_value) 
{ 
  $id_value[$key] = $index_value['idrecipe']; 
  $value_value[$key] = $index_value['value']; 
  $tri_value[$key] = $index_value['tri'];
} 

最佳答案

在第一个 foreach() 循环中,您将迭代主数组,而不是子数组 idrecipe 的值!

foreach($ingredient_difference['idrecipe'] as $value)
{
  echo $value;
}

关于php - 具有关联数组的 PHP foreach 函数的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10299631/

相关文章:

arrays - 如何从多个 BezierPath 创建多个路径

arrays - 子类化 AS3 数组 : how to get array elements (this[0] does not work)?

php - 如何检查变量是否为数组?...或类似数组的东西

php - 如何在 magento 中使用 XML 在 block 之后或之前添加内容

php - Codeigniter:分组依据并从连接表中获取最新记录

c - char *argv[] 和 char **argv 对于 main() 的第二个参数的区别

c# - IEnumerable 是否需要使用 foreach 循环?

c# - 读取包含大量元素的字符串列表 C#

php - 显示帖子某些订单

php - 连接表 - MySQL 和 PHP