Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge subarray values and remove duplicates?

$arr[] = array('A','B');
$arr[] = array('C','B');
...

I need to get the merged result of all sub array of $arr .

And for duplicated entries,should fetch only one.

like image 631
user198729 Avatar asked Jan 26 '10 15:01

user198729


People also ask

How do you merge two arrays of objects in JavaScript and de duplicate items?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do I merge two arrays without duplicates in typescript?

Example 1: Using concat() and for Loop In the above program, the two array elements are merged together and the duplicate elements are removed. Here, The two arrays are merged using the concat() method. The for...of loop is used to loop through all the elements of arr .

How can you remove duplicates in an array?

Given a sorted array, the task is to remove the duplicate elements from the array. Create an auxiliary array temp[] to store unique elements. Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements.


2 Answers

array_unique(array_merge($arr[0], $arr[1]));

or for an unlimited case, I think this should work:

$result_arr = array();
foreach ($arr as $sub_arr) $result_arr = array_merge($result_arr, $sub_arr);
$result_arr = array_unique($result_arr);
like image 199
sprugman Avatar answered Sep 28 '22 09:09

sprugman


OK through another question I found out that the following is actually possible (I tried myself without success, I had the wrong version) if you use PHP version >= 5.3.0:

$merged_array = array_reduce($arr, 'array_merge', array());

If you only want unique values you can apply array_unique:

$unique_merged_array = array_unique($merged_array);

This works if you only have flat elements in the arrays (i.e. no other arrays). From the documentation:

Note: Note that array_unique() is not intended to work on multi dimensional arrays.

If you have arrays in your arrays then you have to check manually e.g. with array_walk:

$unique_values = array();

function unique_value($value, &$target_array) {
    if(!in_array($value, $target_array, true))
        $target_array[] = $value;
}

array_walk($merged_values, 'unique_value', $unique_values);

I think one can assume that the internal loops (i.e. what array_walk is doing) are at least not slower than explicit loops.

like image 32
Felix Kling Avatar answered Sep 28 '22 08:09

Felix Kling