Search code examples
phpmultidimensional-arraynestedarray-difference

Delete duplicates of values of two nested multidimensional arrays


I'm struggling with the array_diff function and another solutions for my problem but nothing gives me the desired effect..

I have two multidimensional arrays (the nested depth not known) that returned from database and will encode and decode to JSON.

The arrays looks like this:

Array ( 
    [0] => Array ( [id] => 1 [lft] => 1  [rgt] => 2  ) 
    [1] => Array ( [id] => 2 [lft] => 3  [rgt] => 4  )
    [2] => Array ( [id] => 3 [lft] => 5  [rgt] => 6  )
    [3] => Array ( [id] => 4 [lft] => 7  [rgt] => 16 )
    [4] => Array ( [id] => 5 [lft] => 8  [rgt] => 9  )
    [5] => Array ( [id] => 6 [lft] => 10 [rgt] => 11 )
    [6] => Array ( [id] => 7 [lft] => 12 [rgt] => 15 )
    [7] => Array ( [id] => 8 [lft] => 13 [rgt] => 14 )
    [8] => Array ( [id] => 9 [lft] => 17 [rgt] => 18 )
)

Array ( 
    [0] => Array ( [id] => 17 [lft] => 1 [rgt] => 2  ) 
    [1] => Array ( [id] => 3  [lft] => 3 [rgt] => 10 )
    [2] => Array ( [id] => 9  [lft] => 4 [rgt] => 9  )
    [3] => Array ( [id] => 24 [lft] => 5 [rgt] => 6  )
    [4] => Array ( [id] => 81 [lft] => 7 [rgt] => 8  )
)

Now i would like to merge this two arrays so that i get the first array without elements that have the same id like elements from the second array. The result should be like this:

Array ( 
    [0] => Array ( [id] => 1 [lft] => 1  [rgt] => 2  ) 
    [1] => Array ( [id] => 2 [lft] => 3  [rgt] => 4  )
    [3] => Array ( [id] => 4 [lft] => 7  [rgt] => 16 )
    [4] => Array ( [id] => 5 [lft] => 8  [rgt] => 9  )
    [5] => Array ( [id] => 6 [lft] => 10 [rgt] => 11 )
    [6] => Array ( [id] => 7 [lft] => 12 [rgt] => 15 )
    [7] => Array ( [id] => 8 [lft] => 13 [rgt] => 14 )
)

For example I have tried is with this modified function an other solution approaches but nothing seems to work. Can anybody help me?


Solution

  • You are right, you need array_udiff.

    Try this:

    $res = array_udiff($array1, $array2, function ($a, $b) {
        if ($a['id'] < $b['id']) {
            return -1;
        } elseif ($a['id'] > $b['id']) {
            return 1;
        } else {
            return 0;
        }
    });