1

ここに私の2つの配列があります:

$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' )
           [1] => Array ( [row_id] => 5 [comment] => 'hello1' ) 
           [2] => Array ( [row_id] => 6 [comment] => 'hello2' ) );

$array2= ( [0] => Array ( [row_id] => 5 [vote] => 1 ) 
           [1] => Array ( [row_id] => 7 [vote] => 1 ) 
           [2] => Array ( [row_id] => 237 [vote] => 0 ) );

の キーと値のペアを $array1に一致さ$array1せて追加したいと思います。$array2[row_id]$array2[vote]$array1[row_id]=$array2[row_id]

これは、出力を次のようにしたい方法です。

$array1 =( [0] => Array ( [row_id] => 237 [comment] => 'hello0' [vote] => 0  )
           [1] => Array ( [row_id] => 5 [comment] => 'hello1' [vote] => 1 ) 
           [2] => Array ( [row_id] => 6 [comment] => 'hello2' [vote] => 1 ) );

これを行うには多くの方法があると確信しているので、計算上最速の考えもいただければ幸いです!

4

2 に答える 2

6
foreach($array1 as $key1=>$value1)
{
  foreach($array2 as $key2=>$value2)
  {
     if($value1['row_id']==$value2['row_id'])
     {
         $value1['vote'] = $value2['vote'];
         $result[$key1][]=$value1;
     }
 }
}

$result is what you need!
于 2012-05-01T15:38:54.617 に答える
2
foreach($array1 as $key1=>$value1)
{
    foreach($array2 as $key2=>$value2)
   {
       if($value1['row_id']==$value2['row_id'])
       {
           if ($value2['vote']) {
               $result[$key1]['vote']=$value2['vote']; // You're assigning the vote value to a new index of 'vote' on the original array.
           } else {
               $result[$key1]['vote'] = 'no vote';
           }
       }
   }
}

これは、Ray Cheng の回答に必要な変更です。

編集した

もう一度編集しました:

データベースからデータを取得する場合、間違いなくレコードを配列として取得できます (調べてみると、丘と同じくらい古いコードが公開されています)。次のステップは、アレイを優先フォーマットに再編成することです。FOREACHはこれに最適です。

// $array1 brought in from some other process
$arrayStorage = array();
foreach ($array1 as $row){ 
    $arrayStorage[$row['row_id']] = array('votes'=>$row['votes'], 'comment'=>$row['comment']);
}

データベースに戻す場合は、元に戻して、必ずキーをもう一度引き抜いてください。

foreach ($arrayStorage as $row_id=>$row_data){ ...

最後の編集:

それぞれのデータベースの両方がデータ用に OP の形式にプルされていると仮定します...

foreach ($array1 as $row){ 
    $arrayStorage[$row['row_id']]['comment'] = $row['comment'];
}

foreach ($array2 as $row){ 
    $arrayStorage[$row['row_id']]['votes'] = $row['votes'];
}
$array1 = $arrayStorage;

// You are going through $array1 and $array2 and creating a placeholder that is built with the $row_id as an associated structure with a comment and vote for each $row_id. This is your final desired array.
于 2012-05-01T17:37:59.833 に答える