简体   繁体   中英

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.

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));

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 (ie 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 eg 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 (ie what array_walk is doing) are at least not slower than explicit loops.

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);

This answer is based on Felix Kling post. It's more accurate version with fixing "non array" sub-elements.

$res = array_reduce($res, function(&$res, $v) {
                            return array_merge($res, (array) $v);
                        }, array());

对于带有 splat 运算符的 PHP 5.6:

array_unique(array_merge(...$arr));

在 PHP 版本>= 5.6处理此问题的一种简单方法是使用 splat 运算符,也称为Argument Unpacking

$arr = array_unique(array_merge(...$arr));

$merged_array = array_reduce($serp_res, 'array_merge', array()); with added quotas,'array_merge', worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM