2

我在 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 的值,但我使用以下代码得到未定义的索引:

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 构造也给出了未定义的索引错误:

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'];
} 
4

2 回答 2

4

在您的第一个foreach()循环中,您遍历主数组而不是子数组的值idrecipe

foreach($ingredient_difference['idrecipe'] as $value)
{
  echo $value;
}
于 2012-04-24T14:09:41.830 回答
2

foreach 构造一个循环。在您的代码中

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

在第一个循环运行中:$recipe_output 是 $ingredient_difference[total_remaining_ingredients] 在第二个循环运行中:$recipe_output 是 $ingredient_difference[idrecipe] 在第三个循环运行中:$recipe_output 是 $ingredient_difference[value]

因为没有

$ingredient_difference['total_remaining_ingredients']['idrecipe']
$ingredient_difference['idrecipe']['idrecipe']
$ingredient_difference['value']['idrecipe']

你得到错误。

要查看 foreach 循环如何工作,请使用http://php.net/manual/de/control-structures.foreach.php上的示例

我期望你想做的是:

foreach($ingredient_difference['idrecipe'] as $value_of_recipe)
{
    echo $value_of_recipe."<br />";
}
于 2012-04-24T14:18:07.613 回答