仅通过ID合并对象

时间:2016-02-04 09:44:43

标签: php

我想要通过数组中的对象的id(2个不同的对象)合并2个数组:

$object1 = new User();
$object2 = new User();
$object3 = new AdminUser();
$object4 = new AdminUser();


$object1->id = "1234";
$object1->name = "testUser1";
$object2->id = "34553";
//the id is like user1 but the username is different
$object3->id = "1234";
$object3->name = "testUser2";
$object4->id = "44234";

$array1  = [$object1,$object2];
$array2  = [$object3,$object1,$object4];

我想要的结果是:

[$object1,$object2,$object4];

我试过了:array_unique(array_merge($array1,$array2), SORT_REGULAR); 我也尝试过:

$result = array_merge( $array1, $array2 );
$result = array_map("unserialize", array_unique(array_map("serialize", $result)));

但它无效

`

2 个答案:

答案 0 :(得分:2)

合并这两个数组后,您可以使用array_reduce

$mergedObjects = array_merge($array1, $array2);
$result = array_reduce($mergedObjects, function ($carry, $user) {
    if (!isset($carry[$user->id])) {
        $carry[$user->id] = $user;
    }
    return $carry;
}, array());

答案 1 :(得分:0)

数组函数仅用于数组,它们不解析数组中对象内的任何内容。你可以做的是将对象id作为数组键推送:

$mainArray = array();
foreach($objects as $object){ //or do it for every object if you create them manually
    array_merge($mainArray, array($object->id => $object);
}

如果密钥(ID)重复,则最新密钥优先。