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]です。2番目のループ実行では$recipe_outputは$ingredient_difference[idrecipe]です。3番目のループ実行では$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 に答える