如何合并两个对象数组

时间:2011-01-18 09:44:57

标签: php

A:

Array ( 
    [0] => gapiReportEntry Object (
        [metrics:private] => Array ( 
            [visits] => 1036 
            [pageviews] => 2046 
            [bounces] => 693 
            [entrances] => 1036 
        ) 
        [dimensions:private] => Array ( 
            [date] => 20110114 
        ) 
    ) 
)

B:

Array ( 
    [0] => gapiReportEntry Object ( 
        [metrics:private] => Array ( 
            [goal1Completions] => 1 
        ) 
        [dimensions:private] => Array ( 
            [date] => 20110114 
        ) 
    ) 
)

C:

Array ( 
    [0] => gapiReportEntry Object ( 
        [metrics:private] => Array ( 
            [visits] => 1036 
            [pageviews] => 2046 
            [bounces] => 693 
            [entrances] => 1036 
            [goal1Completions] => 1
        ) 
        [dimensions:private] => Array ( 
            [date] => 20110114 
        ) 
    ) 
)

我想合并(A,B)并获得C。

6 个答案:

答案 0 :(得分:1)

了解数组的合并

采用示例

$arr1 = (1, 2, 3, 4, 5);
$arr2 = (10, 20, 30, 40, 50);

$arr3 = array_merge ($arr1 , $arr2 );
print_r($arr3); //(1,2,3,4,5,10,20,30,40,50)

shuffle($arr3 );//(1,10,2,20,3,30,4,40,5,50)

答案 1 :(得分:1)

我不知道这个问题的原因,但这里有解决方案:

//lets think $A - A - array, $B - B array
$a1 = (array)$A[0];
$b1 = (array)$B[0];

$c = array_merge($a1, $b1);

print_r($result);

//shows your Array, but not object.
//You can create object using printed resulted array.

答案 2 :(得分:0)

您可以使用PHP中提供的array_merge()函数

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

答案 3 :(得分:0)

首先,我并不是说这是对这个问题的所有答案的结束,但是已经有九个月了,我觉得这个问题没有得到解答,但确实有它的用途。

据我所知,你有两个(或更多)数组,由多个对象组成,这些对象拥有同一个对象的不同属性。例如在下一个例子中:

ArrayedObjects1=array(   
    [0]=>stdClass Object
       (
           [id] => 1
           [name] => foo
       )
    [1] => stdClass Object
       (
           [id] => 51
           [name] => bar
       )
)
ArrayedObjects2=array(   
    [0]=>stdClass Object
      (
          [length] => 195
          [color] => blue
      )
    [1] => stdClass Object
      (
          [length] => 100
          [name] => purple
      )
)

用例可以用于非常大的项目,其中多个数据库用于存储同一对象的单个值,并且无法进行简单的连接查询。

这两个数组可以通过我使用的两个函数连接起来,这样就可以将未指定数量的数组连接在一起。

class FooBar {

    public function mergeArrayedObjects(){
       #    We generate a new empty array to return from the function, to which we merge the existing arrays
       $returnResponse=array();

        #   Then we establish the the number of arguments passed to the function
        $numArgs=func_num_args();

        #   As objects are stored within an array of equal length, we loop through the first
        for($i=0;$i<count(func_get_arg(0));$i++){
            #   For each key within the array we merge all existing arrays. We get this number from the number of arguments
            #   First we check if there already exists an entry into the returnRespone array with the current key. Two choices:
            #       Case 1 => no: create one by merging the first two arrays into this new array
            #       Case 2 => yes: merge the existing entry with the next array and recreate it

            #   BTW we correct $numArgs in the for-loop, as we add 1 to $j in the second case to exclude duplication of work
            for($j=0;$j<($numArgs-1);$j++){
                #   Seems like you can't check on empty with func_get_arg(), so store it in a variable
                #   We do this as no merge is needed if the array is empty, or the key is empty
               $isempty=func_get_arg($j+1);
               if(!empty($isempty)||!empty($isempty[$i])){
                   if(!$returnResponse[$i]){ 
                        $array1=func_get_arg($j);
                        $array2=func_get_arg($j+1);

                        $returnResponse[$i]=self::mergeObjects($array1[$i],$array2[$i]);
                    }
                    else{
                        $array1=func_get_arg($j+1);
                        $returnResponse[$i]=self::mergeObjects($returnResponse[$i],$array1[$i]);
                    }
                }
            }

        }

        #   Then we return the arrayed objects
        return $returnResponse;
   }
   public function mergeObjects($obj1,$obj2){
        #   Function to merge objects
        $merged_obj=  (object) array_merge((array) $obj1, (array) $obj2);
        return $merged_obj;
   }
 }                           

返回以下数组:

$joinArrays=new FooBar;
$joinedArray=$joinArrays->mergeArrayedObjects(ArrayedObjects1,ArrayedObjects2);

$joinedArray=array(   
    [0]=stdClass Object
        (
            [id] => 1
            [name] => foo
            [length] => 195
            [color] => blue
        )
    [1] => stdClass Object
        (
            [id] => 51
            [name] => bar
            [length] => 100
            [name] => purple
         )
)

正如我所说,这可以用于无限数量的数组。如果有更快的方式,请随时告诉我。我需要这个来加入不同数据库之间的查询结果,所以我只是写信,因为这样做并且同时非常灵活。

这也可以扩展到检查对象中的一个条目是否是一个数组并且执行一个array_merge ofcourse,它会添加两行代码。

答案 4 :(得分:0)

对于您的具体情况,我们要清楚您要合并两个数组,这些数组包含在数组中包含的对象中。话虽如此,知道如何使用结果对象(你只需要来自那些数组的数据,或者对象实例的其余部分是否重要?)将有助于给你一个答案。 TL; DR:

$temparray = array_merge($A[0]->metrics, $B[0]->metrics);
$C->methodToSetMetricsArray($temparray);

上述methodToSetMetricsArray()执行上述内容的情况,因为数组为private且无法直接设置。

答案 5 :(得分:0)

您希望与自定义Php类进行深度合并。内置没有这样的功能。

但是如果你可以将你的Php对象转换为数组,你可以利用array_merge_recursive函数(参见http://php.net/manual/fr/function.array-merge-recursive.php)。