Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP merge arrays with only NOT DUPLICATED values

Tags:

arrays

merge

php

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"      }  }  
like image 641
itsme Avatar asked May 13 '12 14:05

itsme


People also ask

How do I merge two arrays of objects without duplicates?

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.

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.

What is the best method to merge two PHP objects?

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.

How do I combine two arrays?

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.


2 Answers

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)); 
like image 78
Jeroen Avatar answered Sep 23 '22 13:09

Jeroen


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 ) 
like image 31
Luca Rainone Avatar answered Sep 23 '22 13:09

Luca Rainone