I need to merge two arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values when merged.
How can i do that?
This is the array example:
First array
array(3) { [0]=> object(stdClass)#17 (1) { ["email"]=> string(7) "gffggfg" } [1]=> object(stdClass)#18 (1) { ["email"]=> string(6) "[email protected]" } [2]=> object(stdClass)#19 (1) { ["email"]=> string(6) "wefewf" } }
Second array
array(3) { [0]=> object(stdClass)#17 (1) { ["email"]=> string(7) "[email protected]" } [1]=> object(stdClass)#18 (1) { ["email"]=> string(6) "wefwef" } [2]=> object(stdClass)#19 (1) { ["email"]=> string(6) "wefewf" } }
ES5 Solutionconcat() can be used to merge multiple arrays together. But, it does not remove duplicates. filter() is used to identify if an item is present in the “merged_array” or not. Just like the traditional for loop, filter uses the indexOf() method to judge the occurrence of an item in the merged_array.
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.
Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
You can combine the array_merge()
function with the array_unique()
function (both titles are pretty self-explanatory)
$array = array_unique (array_merge ($array1, $array2));
If I understand the question correctly:
$a1 = Array(1,2,3,4); $a2 = Array(4,5,6,7); $array = array_diff(array_merge($a1,$a2),array_intersect($a1,$a2)); print_r($array);
return
Array ( [0] => 1 [1] => 2 [2] => 3 [5] => 5 [6] => 6 [7] => 7 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With