合并数组相同的键

时间:2018-06-27 07:23:27

标签: php arrays laravel collections laravel-5.5

I have following 2 arrays:

$arr1 = [
   0 => [
      'id' => 1,
      'name' => 'Peter',
   ],
   1 => [
      'id' => 2,
      'name' => 'John',
   ]
]

$arr2 = [
   0 => [
      'id' => 1,
      'surname' => 'Newman',
   ],
   1 => [
      'id' => 2,
      'surname' => 'Cena',
   ]
]

我想做的是合并引用相同键的这些数组。在这种情况下,我想在id匹配的地方合并它们。所以我期望的输出是:

$finalArr = [
       0 => [
          'id' => 1,
          'name' => 'Peter',
          'surname' => 'Newman',
       ],
       1 => [
          'id' => 2,
          'name' => 'John',
          'surname' => 'Cena',
       ]
    ]

我正在使用laravel,但是语言应该没什么太大的关系。如果可能的话,我想使用collections

3 个答案:

答案 0 :(得分:1)

您可以使用array_maparray_merge并检查键是否匹配:

$finalArr = array_map(function($x) use ($arr2) {
    foreach($arr2 as $b) {
        if ($x["id"] === $b["id"]) {
            return array_merge($x, $b);
        }
    }
    return $x;
}, $arr1);

var_dump($finalArr);

Demo

答案 1 :(得分:0)

尝试这个:

foreach ($arr2 as $key2 => $value2) {
    foreach ($arr1 as $key1 => $value1) {
        if($value2['id'] == $value1['id']){
            $arr1[$key1] = array(
                'id' =>  $value1['id'],
                'name' => $value1['name'],
                'surname' => $value2['surname']
            );
        }
    }
}

答案 2 :(得分:0)

$arr1 = [
  0 => [
    'id' => 1,
    'name' => 'Peter',
  ],
  1 => [
    'id' => 2,
    'name' => 'John',
  ]
];

$arr2 = [
  0 => [
    'id' => 1,
    'surname' => 'Newman',
  ],
  1 => [
    'id' => 2,
    'surname' => 'Cena',
  ]
];

// First, I create a new array
$new_array = array();

// Now I loop throught first array and merge each array by key
foreach ($arr1 as $key => $value) {
    // If I just check if second array has the key so you can merge both
    // If you are 100% sure that both array has same key, no need to use isset()
    if (isset($arr2[$key])) {
        $new_array[$key] = array_merge($arr1[$key], $arr2[$key]);
    }
}

var_dump($new_array);

输出为:

array (size=2)
  0 => 
    array (size=3)
      'id' => int 1
      'name' => string 'Peter' (length=5)
      'surname' => string 'Newman' (length=6)
  1 => 
    array (size=3)
      'id' => int 2
      'name' => string 'John' (length=4)
      'surname' => string 'Cena' (length=4)