PHP合并数组的值相同

时间:2013-03-26 17:07:08

标签: php arrays array-merge

我有两个大型数组,大约有1000个密钥,每天都在增长。 如何在array1[]['uid']array2[][7]

中将这些数组合并为一个值

请注意,正确的值可以是array1[45]['uid']array2[155][7]array1[444]['uid']array2[666][7]等。

array1
    0 => 
    array
      'login' => string '104' (length=5)
      'uid' => string '1363861889.100' (length=14)
    1 => 
    array
      'login' => string '131' (length=5)
      'uid' => string '1363863722.126' (length=14)
    etc...

和另一个

array2
     0 => 
    array
      0 => string '2013' (length=4)
      1 => string '03' (length=2)
      2 => string '25' (length=2)
      3 => string '15' (length=2)
      4 => string '39' (length=2)
      5 => string '49' (length=2)
      6 => string 'anonymous' (length=9)
      7 => string '1363863722.126' (length=19)
    1 => 
    array
      0 => string '2013' (length=4)
      1 => string '03' (length=2)
      2 => string '25' (length=2)
      3 => string '12' (length=2)
      4 => string '39' (length=2)
      5 => string '42' (length=2)
      6 => string 'anonymous' (length=9)
      7 => string '1363861889.100' (length=19)
    etc...

array1[0]['uid']array2[1][7]具有相同的值 我想得到:

 array
      0 => string '2013' (length=4)
      1 => string '03' (length=2)
      2 => string '25' (length=2)
      3 => string '12' (length=2)
      4 => string '39' (length=2)
      5 => string '42' (length=2)
      6 => string 'anonymous' (length=9)
      7 => string '1363861889.100' (length=19)
      'login' => string '104' (length=5)
      'uid' => string '1363861889.100' (length=14)

2 个答案:

答案 0 :(得分:2)

$array1_inverted = array();
foreach ($array1 as $subarray) {
  $array1_inverted[$subarray['uid']] = $subarray;
}
foreach ($array2 as &$element) {
  $array1_element = $array1_inverted[$element[7]];
  $element['uid'] = $array1_element['uid'];
  $element['login'] = $array1_element['login'];
}

DEMO

答案 1 :(得分:1)

foreach($array1 as $value)
{
  foreach($array2 as $value1)
  {
    if($value['uid'] == $value1[7])
  {
     $value1['uid'] = $value['uid'];
     $value1['login'] = $value['login'];
  }
 }
}

尝试同时我会想到一些更好的替代方案