tags:

views:

499

answers:

3
$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.

+4  A: 
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);
sprugman
It can have more than 2 sub arrays.
You can supply the arguments with how many array's you like
Anthony Forloney
The number of sub arrays is dynamic.
Despite the author only giving $arr 0 + 1 as an example, I think they needs a solution to accommodate for all child items of $arr.
ILMV
I updated to add the unlimited case.
sprugman
Is there a way to do it other than loop?
why? what's wrong with a loop? I suppose you could use some kind of mapping function. Look at the array section of the php docs for other ideas. http://www.php.net/manual/en/ref.array.php
sprugman
If the number of arrays are dynamic, I think loops could be the best choice. Why would you not want a loop?
Anthony Forloney
Is there a array function that can handle this problem?
I'm starting to feel like we're helping someone with their homework...
sprugman
array_walk() is a possibility, but it's more overhead
sprugman
It is still not correct, it has to be `$result_arr = array_merge($result_arr, $sub_arr);`
Felix Kling
oh, yeah. oops.
sprugman
+2  A: 

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.

Felix Kling
I don't think $merged_array = array_merge($arr); will actually break up the sub-arrays, which I'm pretty sure is what the OP was asking for.
sprugman
good point. fixed.
sprugman
+3  A: 

If you really don't want to loop, try this:

$arr[] = array('A','B');
$arr[] = array('C','B');
$arr[] = array('C','D');
$arr[] = array('F','A');
$merged = array_unique(call_user_func_array('array_merge', $arr));
bish