Problem
Hello, I’m attempting to combine two arrays and remove duplicate values from the final array.
Here’s my first array:
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
)
And here’s my second array:
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’m using array merge to combine the two arrays into one. Its output looks like 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 remove these duplicate entries or can I remove these before merging… Pleas help.. Thanks!!!!!!!
Asked by Ravi
Solution #1
array_unique(array_merge($array1,$array2), SORT_REGULAR);
http://se2.php.net/manual/en/function.array-unique.php
Answered by C. E.
Solution #2
As previously stated, array unique() can be utilized when dealing with simple data. The things aren’t easy to manipulate.
When PHP attempts to merge the arrays, it compares the array members’ values. If a member is an object, it can’t access its value, so it falls back on the spl hash. More information about spl object hash may be found here.
jects, regardless of how valuable their properties are.
You should take care of the situation on your own.
If you’re intending to merge multidimensional arrays, array merge recursive() is a better option than array merge ().
Answered by Nikola Petkanski
Solution #3
It will combine two arrays and eliminate 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);
?>
Take a look at this link1
Answered by Daxen
Solution #4
Use the array unique method if possible ()
This eliminates duplicate data from your arrays’ list.
Answered by Jhonathan H.
Solution #5
You can use this code to achieve your goal. Duplicates will be removed.
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_unique(array_merge($a1,$a2));
print_r($result);
Answered by Usman Haider
Post is based on https://stackoverflow.com/questions/13469803/php-merging-two-arrays-into-one-array-also-remove-duplicates