Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two arrays of object in PHP

I have the following two arrays of objects:

First Array: $array1

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 102
            [name] => Ibrahim
        )

    [2] => stdClass Object
        (
            [id] => 101
            [name] => Sumayyah
        )
)

Second Array: $array2

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 103
            [name] => Yusuf
        )
)

I want to merge these two object arrays (removing all duplicates) and sorted according to id.

Desired output:

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 101
            [name] => Sumayyah
        )

    [2] => stdClass Object
        (
            [id] => 102
            [name] => Ibrahim
        )

    [3] => stdClass Object
        (
            [id] => 103
            [name] => Yusuf
        )
)
like image 525
M. Ahmad Zafar Avatar asked Aug 09 '12 06:08

M. Ahmad Zafar


People also ask

How can I merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

How do you combine two objects in an array?

Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

How do I combine multiple objects into one?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.


3 Answers

These 3 simple steps did the work:

//both arrays will be merged including duplicates $result = array_merge( $array1, $array2 ); //duplicate objects will be removed $result = array_map("unserialize", array_unique(array_map("serialize", $result))); //array is sorted on the bases of id sort( $result ); 

Note: Answer by @Kamran helped me come to this simple solution

like image 53
M. Ahmad Zafar Avatar answered Oct 09 '22 23:10

M. Ahmad Zafar


UPDATE

I am posting the entire code listing here now instead of the previously posted main code, printing both input and output. You can simply copy and paste this code to test.

<?php  function array_to_object($arr) {     $arrObject = array();     foreach ($arr as $array) {         $object = new stdClass();         foreach ($array as $key => $value) {             $object->$key = $value;         }         $arrObject[] = $object;     }      return $arrObject; }  function super_unique($array) {     $result = array_map("unserialize", array_unique(array_map("serialize", $array)));     foreach ($result as $key => $value)  {         if ( is_array($value) ) {           $result[$key] = super_unique($value);         }     }     return $result; }  function merge_arrays($arr1, $arr2) {     $arr1 = (array)$arr1;     $arr2 = (array)$arr2;     $output = array_merge($arr1, $arr2);     sort($output);     return super_unique($output); }  $array1 = array(         array("id" => "100", "name" => "muhammad"),          array("id" => "102", "name" => "ibrahim"),          array("id" => "101", "name" => "summayyah"),      ); $array1 = array_to_object($array1);  print "<h3>Your array 1</h3>"; print "<pre>"; print_r($array1); print "</pre>";  $array2 = array(         array("id" => "100", "name" => "muhammad"),          array("id" => "103", "name" => "yusuf"),      ); $array2 = array_to_object($array2);  print "<h3>Your array 2</h3>"; print "<pre>"; print_r($array2); print "</pre>";  $result = merge_arrays($array1, $array2);  print "<h3>Your desired output</h3>"; print "<pre>"; print_r($result); print "</pre>"; 

it will output the following:

Your array 1 Array (     [0] => stdClass Object         (             [id] => 100             [name] => muhammad         )      [1] => stdClass Object         (             [id] => 102             [name] => ibrahim         )      [2] => stdClass Object         (             [id] => 101             [name] => summayyah         )  )  Your array 2 Array (     [0] => stdClass Object         (             [id] => 100             [name] => muhammad         )      [1] => stdClass Object         (             [id] => 103             [name] => yusuf         )  )  Your desired output Array (     [0] => stdClass Object         (             [id] => 100             [name] => muhammad         )      [2] => stdClass Object         (             [id] => 101             [name] => summayyah         )      [3] => stdClass Object         (             [id] => 102             [name] => ibrahim         )      [4] => stdClass Object         (             [id] => 103             [name] => yusuf         )  ) 
like image 41
Software Guy Avatar answered Oct 10 '22 00:10

Software Guy


Assignments:

  1. Merge
  2. Remove Duplicates
  3. Sort by id

The good news is: Assigning temporary keys using id values does all of the hard work for you. No serializing is needed.

  • array_merge() joins the arrays together.
  • array_column() with a null 2nd parameter leaves the objects unmodified and id as the 3rd parameter assigns the temporary keys. Because arrays cannot have duplicate keys, duplicate objects are weeded out in this step.
  • Now that we have keys, ksort() avoids calling the more convoluted usort() to sort by id ascending.
  • Finally, call array_values() to re-index the resultant array (remove the temporary keys).

Code: (Demo)

$array1 = [
    (object) ['id' => 100, 'name' => 'Muhammad'],
    (object) ['id' => 102, 'name' => 'Ibrahim'],
    (object) ['id' => 101, 'name' => 'Sumayyah']
];

$array2 = [
    (object) ['id' => 100, 'name' => 'Muhammad'],
    (object) ['id' => 103, 'name' => 'Yusuf']
];

$merged_keyed = array_column(array_merge($array1,$array2), NULL, 'id');
ksort($merged_keyed);
print_r(array_values($merged_keyed));

Output:

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )    
    [1] => stdClass Object
        (
            [id] => 101
            [name] => Sumayyah
        )    
    [2] => stdClass Object
        (
            [id] => 102
            [name] => Ibrahim
        )    
    [3] => stdClass Object
        (
            [id] => 103
            [name] => Yusuf
        )    
)
like image 23
mickmackusa Avatar answered Oct 09 '22 22:10

mickmackusa