PHP - Combining two arrays into one array (also Remove Duplicates)

Hi, I am trying to combine two arrays, I also want to remove duplicate values ​​from the final array.

Here are my arrays 1:

Array ( [0] => stdClass Object ( [ID] => 749 [post_author] => 1 [post_date] => 2012-11-20 06:26:07 [post_date_gmt] => 2012-11-20 06:26:07 ) 

This is my array 2:

 Array ( [0] => stdClass Object ( [ID] => 749 [post_author] => 1 [post_date] => 2012-11-20 06:26:07 [post_date_gmt] => 2012-11-20 06:26:07 ) 

I use array_merge to merge both arrays into one array. he gives a result similar to this

 Array ( [0] => stdClass Object ( [ID] => 749 [post_author] => 1 [post_date] => 2012-11-20 06:26:07 [post_date_gmt] => 2012-11-20 06:26:07 [1] => stdClass Object ( [ID] => 749 [post_author] => 1 [post_date] => 2012-11-20 06:26:07 [post_date_gmt] => 2012-11-20 06:26:07 ) 

I want to delete this duplicate entry or delete it before merging ... Please help .. Thank you !!!!!!!

+56
arrays php multidimensional-array wordpress
Nov 20 '12 at 9:10
source share
4 answers
 array_unique(array_merge($array1,$array2), SORT_REGULAR); 

http://se2.php.net/manual/en/function.array-unique.php

+122
Nov 20 '12 at 9:14
source share

try using array_unique()

this eliminates duplicate data inside the list of your arrays.

+3
Nov 20. '12 at 9:15
source share

As already mentioned, array_unique () can be used, but only when working with simple data. Objects are not so easy to handle.

When php tries to combine arrays, it tries to compare the values ​​of the elements of the array. If the element is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.

Simply put, if you have two objects, instances of the same class, and if one of them is not a reference to the other, you will get two objects, regardless of their properties.

To make sure you don't have duplicates in the combined array, Imho you have to handle the case yourself.

Also, if you are going to combine multidimensional arrays, consider array_merge_recursive () over array_merge () .

+3
Nov 20 '12 at 9:20
source share

Will merge two arrays and remove duplicates

 <?php $first = 'your first array'; $second = 'your second array'; $result = array_merge($first,$second); print_r($result); $result1= array_unique($result); print_r($result1); ?> 

Try this link1 link

+2
Nov 20 '12 at 9:16
source share



All Articles