How to merge subarray in PHP most easily?

后端 未结 7 518
渐次进展
渐次进展 2020-12-03 22:32
$arr[] = array(\'A\',\'B\');
$arr[] = array(\'C\',\'B\');
...

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

And f

7条回答
  •  一整个雨季
    2020-12-03 23:07

    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.

提交回复
热议问题