Hi I’m Trying to merge two arrays and also want to remove duplicate values from final Array.
Here is my Array 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
)
And 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’m using array_merge
for merging both arrays into one array. it is giving output 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!!!!!!!
http://se2.php.net/manual/en/function.array-unique.php
As already mentioned, array_unique() could be used, but only when dealing with simple data. The objects are not so simple to handle.
When php tries to merge the arrays, it tries to compare the values of the array members. If a member is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.
Simply told if you have two objects, instances of the very same class and if one of them is not a reference to the other one – you will end up having two objects, no matter the value of their properties.
To be sure that you don’t have any duplicates within the merged array, Imho you should handle the case on your own.
Also if you are going to merge multidimensional arrays, consider using array_merge_recursive() over array_merge().
It will merger two array and remove duplicate
Try this link
link1
try to use the
array_unique()
this elminates duplicated data inside the list of your arrays..
Merging two array will not remove the duplicate you can try the below example to get unique from two array
You can use this code to get the desired result. It will remove duplicates.
In my case I had to use
->toArray()
which results of combining both of these answers
https://stackoverflow.com/a/13469882/5675325
https://stackoverflow.com/a/40020800/5675325
The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case
If you are able output your value to the keys of your arrays instead (e.g ->pluck(‘name’, ‘id’)->toArray() in Eloquent), you can use the following merge method instead
Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps
In addition to the answer above, from PHP 7.4 you can make use of the spread operator: