Array_merge_recursive gives me repeat data, how to remove it

Sadly, array_replace_recursive (PHP 5.3.0)­Docs does not work (Demo).

Luckily Tim Cooper pointed that out and made some suggestion. I was not very creative with my new suggestion, so it's highly influenced by his solution:

$result = array_merge_recursive($a, $b);

array_walk($result, function(&$v) {
    $v = array_map('array_unique', $v);
});

New Demo


Use array_replace_recursive instead of array_merge_recursive.


The the following should work for you:

array_walk($arr, function(&$data, $key) {
    foreach ($data as &$arr) {
        $arr = array_values(array_unique($arr));
    }
});

Result:

Array
(
    [group1] => Array
        (
            [names] => Array
                (
                    [0] => g1name1
                    [1] => g1name2
                    [2] => g1name3
                )
            [extras] => Array
                (
                    [0] => g1extra1
                )
        )
    [group2] => Array
        (
            [names] => Array
                (
                    [0] => g2name1
                )
        )
    [group3] => Array
        (
            [names] => Array
                (
                    [0] => g3name1
                )
        )
)

Tags:

Php

Arrays