phpmergeclosuresarray-merge

Merge two 2d arrays and remove duplicate rows


I searched a lot of SOF threads and no one seems to stick to my problem. What's kind of wired because this should be a well discussed question :)

Maybe I'm seeking for the wrong thing...

Scenario:

I have 2 arrays

$a = [ 
    ['id' => 5, 'name' => 'bruce'],
    ['id' => 7, 'name' => 'wayne']
];
// 2 elements

and

$b = [
    ['id' => 6, 'name' => 'chuck'],
    ['id' => 8, 'name' => 'norris'],
    ['id' => 7, 'name' => 'wayne'] //also exists in array $a
];
// 3 elements

My goal is

$c = [
    ['id' => 6, 'name' => 'chuck'],
    ['id' => 8, 'name' => 'norris'],
    ['id' => 7, 'name' => 'wayne'],
    ['id' => 5, 'name' => 'bruce']
];
// 4 elements (no duplicates)

I really don't care about the order inside the array(s) but I want to merge both into one, without having duplicates.

I tried array_merge and array_merge_recursive. No one works. Probably because the functions doesn't know the identifier which identifies each entry. Is there an easy solution or do I really have to create an own method/function for this?

Maybe there is a closure that I could use?


Solution

  • You can do this with very simple inbuilt function of PHP

    $c = array_unique(array_merge($a,$b), SORT_REGULAR);
    print_r( $c )
    

    The output of the print_r is

    Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => bruce
            )
    
        [1] => Array
            (
                [id] => 7
                [name] => wayne
            )
    
        [2] => Array
            (
                [id] => 6
                [name] => chuck
            )
    
        [3] => Array
            (
                [id] => 8
                [name] => norris
            )
    
    )