合并基于相同键的数组元素

时间:2016-06-17 09:39:03

标签: php json merge

我正在寻找最佳解决方案,根据2个数组之间的键值与具有公共键的元素进行“合并”。

输入:

Array1 => [{"id" : "1", "LastName":"Jackson"}, {"id" : "2", "LastName":"Bross"} ]

Array2 =>[{"id" : "1", "FirstName":"Mickael"},{"id" : "2", "FirstName":"Mario"} ]

输出:

[{"id" : "1", "FirstName":"Mickael", "LastName":"Jackson"},
{"id" : "2", "FirstName":"Mario", "LastName":"Bross"} ]

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我认为内部数据是对象,所以我们可以使用foreach,如果id匹配,则按object->key = value格式分配对象数据

foreach ($array1 as $key => $value) {
    foreach ($array2 as $k => $v) {
        if($value->id == $v->id){
            $array1[$key]->FirstName = $v->FirstName;
        }
    }
}
var_dump($array1);

//输出

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => string '1' (length=1)
      public 'LastName' => string 'Jackson' (length=7)
      public 'FirstName' => string 'Mickael' (length=7)
  1 => 
    object(stdClass)[2]
      public 'id' => string '2' (length=1)
      public 'LastName' => string 'Bross' (length=5)
      public 'FirstName' => string 'Mario' (length=5)

答案 1 :(得分:0)

请注意,为了做到这一点,你必须在姓氏和名字数组上拥有相同数量的元素:

$lastNames = array(
    array(
        'id' => 1,
        'lastName' => 'Kent'
    ),
    array(
        'id' => 2,
        'lastName' => 'Snow'
    ),
    array(
        'id' => 3,
        'lastName' => 'Parker'
    ),
);
$firstNames = array(
    array(
        'id' => 1,
        'firstName' => 'Clark'
    ),
    array(
        'id' => 2,
        'firstName' => 'John'
    ),
    array(
        'id' => 3,
        'firstName' => 'Peter'
    ),
);

$people = array();
foreach($firstNames as $key => $data) {
    $people[] = array(
        'id' => $data['id'],
        'FirstName' => $data['firstName'],
        'LastName' => $lastNames[$key]['lastName']
    );
}

print_r($people);

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [FirstName] => Clark
            [LastName] => Kent
        )

    [1] => Array
        (
            [id] => 2
            [FirstName] => John
            [LastName] => Snow
        )

    [2] => Array
        (
            [id] => 3
            [FirstName] => Peter
            [LastName] => Parker
        )

)