使用相同的键合并两个数组

时间:2013-02-13 12:09:28

标签: php arrays

我需要帮助合并两个数组。假设我有以下数组:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
    )

)

第二个:

Array
(
    [6] => Sit dolor
    [4] => nostrud exercitation ullamco
    [3] => uuntur magni dolores
    [2] => corporis suscipit laboriosam
    [7] =>  quia non numquam eius modi tempora
 )

期望的输出是:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
        [new_key] => uuntur magni dolores
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
        [new_key] => corporis suscipit laboriosam
    )
)

我一直在尝试使用array_diff_key()方法比较数组,而不是在某个循环中合并数组,但我无法使其正常工作。有没有内置的PHP函数,还是我应该自己编写?如果是这样,你能帮助我获得理想的结果吗?非常感谢任何帮助。

4 个答案:

答案 0 :(得分:5)

你需要的只是

$data = array_map(function ($v) use($new) {
    isset($new[$v['id']]) and $v['new_key'] = $new[$v['id']] ;
    return $v;
}, $data);

var_dump($data);

输出(DEMO

array (size=2)
  3 => 
    array (size=4)
      'id' => int 3
      'name' => string 'Lorem' (length=5)
      'type' => string 'pl' (length=2)
      'new_key' => string 'uuntur magni dolores' (length=20)
  2 => 
    array (size=4)
      'id' => int 2
      'name' => string 'Ipsum' (length=5)
      'type' => string 'pl' (length=2)
      'new_key' => string 'corporis suscipit laboriosam' (length=28)

答案 1 :(得分:2)

您可以简单地遍历第一个数组:

foreach ($arr1 as $key=> $item) {
    $arr1[$key]['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
}

或者

foreach ($arr1 as &$item) { //just for fun
    $item['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
}

但似乎您的数据来自数据库。如果我是对的,你最好使用sql JOIN

答案 2 :(得分:0)

你也可以这么简单地做

foreach($arr1 as $key => $arr) {

        $arr1[$key]['new_key'] = isset($arr2[$key])?$arr2[$key]:'';
}

答案 3 :(得分:0)

<?php
$first_array  = Array("3" => Array("id" => 3,"name" => "Lorem","type" => "pl"),
                      "2" => Array("id" => 2,"name" => "Ipsum","type" => "pl")
                     );

$sec_array   = Array("6" => "Sit dolor",
                    "4" => "nostrud exercitation ullamco",
                    "3" => "uuntur magni dolores",
                    "2" => "corporis suscipit laboriosam",
                    "7" =>  "quia non numquam eius modi tempora",
                 );

$res_array   = array();
foreach($first_array as $key=>$val){
     if(array_key_exists($key,$sec_array)){
        $val["new_key"] = $sec_array[$key];
     }
     $res_array[$key]   = $val;
}

echo "<pre>";
print_r($res_array);
?>