在PHP中合并2个对象数组

时间:2015-01-29 23:16:19

标签: php arrays

如何合并array1和2?

ARRAY1

Array
(
    [0] => stdClass Object
    (
        [name] => bob
        [id] => 84569354306
        [contacts] => Array
        (
            [0] => none
        )
    )
    [1] => stdClass Object
    (
        [name] => jill
        [id] => 456745742
        [contacts] => Array
        (
            [0] => none
        )
    )
)

数组2

Array
(
    [0] => stdClass Object
    (
        [name] => bob
        [id] => 84569354306
        [pid] => 1
        [lang] => eng;
        [location] =>
    )
    [1] => stdClass Object
    (
        [name] => jill
        [id] => 456745742
        [pid] => 2
        [lang] => eng;
        [location] =>
    )
)

结果数组:

Array
(
    [0] => stdClass Object
    (
        [name] => bob
        [id] => 84569354306
        [pid] => 1
        [lang] => eng;
        [location] =>
        [contacts] => Array
        (
            [0] => none
        )
    )
    [1] => stdClass Object
    (
        [name] => jill
        [id] => 456745742
        [pid] => 2
        [lang] => eng;
        [location] =>
        [contacts] => Array
        (
            [0] => none
        )
    )
)

我尝试了一个array_merge(),似乎在数组中彼此相邻添加对象,而不是合并对象。

我非常确定this question与我需要的相似,但我对简单的foreach循环有困难。

2 个答案:

答案 0 :(得分:8)

您可以将两个对象强制转换为数组,然后重新强制转换回对象。一般语法是:

$merged = (object)array_merge_recursive((array)$firstObj, (array)$secondObj);
                              ^
                              | note the recursive in your case

另外,如果你使用这样的对象,你可能只需要坚持使用数组。用对象

来做这样的事情几乎没有任何意义

有多个项目

如果你有多个项目,你只需要在循环中包装我的脚本:

function myCustomMerge($array1, $array2) {
   assert('count($array1) == count($array2)');
   $result = array();
   foreach($array1 as $k=>$v) {
    $item = array_merge_recursive((array)$array1[$k], (array)$array2[$k]);
    $result[]=$item; // use (object)$item if you need objects
   }
   return $result;
}

无需投射的解决方案

如果您不想在数组和对象之间来回转换,可以使用get_object_vars()

$obj2props = get_object_vars($obj2);
foreach ($obj2props as $prop => $value) {
    $obj1->$prop = $value;
}
return $obj;

答案 1 :(得分:4)

另一种方法:

function merge_values(){
    $list = func_get_args();
    while( count( $list ) > 1 ){
        $array1 = array_shift( $list );
        $array2 = array_shift( $list );

        $merged_array = $array1;
        foreach( $array2 as $key => $value ){
            $merged_array[$key] = array_merge( (array)$value, (array)$merged_array[$key] );
            if( is_object( $value ) || is_object( $array1[$key] ) ){
                $merged_array[$key] = (object)$merged_array[$key];
            }
        }

        array_unshift( $list, $merged_array );
    } 
    return current( $list );
}

$merged = merge_values( $array1, $array2 );