如何在 PHP 中将值从一个数组添加到另一个数组,当它们的键值对匹配时


How in PHP to add values from one array to another when their key value pairs match?

这是我的两个数组:

$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 ) );

我想在[row_id]上匹配$array1$array2并添加$array2 [vote]键/值对到 $array 1,其中$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 ) );

我相信有很多方法可以做到这一点,所以关于最快计算的想法也将不胜感激!

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!
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';
           }
       }
   }
}

这是雷程的回答中需要改变的地方。

编辑

再次编辑:

从数据库中提取数据时,您绝对可以将记录作为数组获取(查找它,它和山丘一样古老,代码就在那里)。下一步是将数组重新组织为首选格式。 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.