1

这是我的两个数组:

$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并添加$array2的键/值对 到 $array1 哪里[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 回答