0

How to remove dulicate keys from multidimensional array?

My array is as follows:

$array = [[0, 1, 2, 3, 4], [1, 2, 3, 4, 6]];

My desired array should be:

$array = [[0, 1, 2, 3, 4], [6]];
ceng
  • 128
  • 3
  • 17
  • See this post: https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php – Cblopez Apr 19 '20 at 16:52
  • 1
    Does this answer your question? [How to remove duplicate values from a multi-dimensional array in PHP](https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – Cblopez Apr 19 '20 at 16:53

3 Answers3

1

Here's a quick and dirty solution for you:

Walk through every element of the array recursively and if you've not seen an element set it to null (unsetting it doesn't work for some reason). Then filter the resulting sub-arrays.

$array = [[0, 1, 2, 3, 4], [1, 2, 3, 4, 6]];
$seen = [];
array_walk_recursive($array, function (&$v) use (&$seen) {
    if (!array_key_exists($v, $seen) {
       $seen[$v] = true;
    } else {
       $v = null;
    }
});
$final = array_map('array_filter', $array);
apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

If the functions array_diff() and array_values​​() are used, the solution can be delivered in one line of code:

$array = [[0, 1, 2, 3, 4], [1, 2, 3, 4, 6]];

$array[1] = array_values(array_diff($array[1],$array[0]));

var_export($array);

Output:

array (
  0 => 
  array (
    0 => 0,
    1 => 1,
    2 => 2,
    3 => 3,
    4 => 4,
  ),
  1 => 
  array (
    0 => 6,
  ),
)
jspit
  • 7,276
  • 1
  • 9
  • 17
0

$serialize=array_map('serialize',$array);
$unique=array_unique($serialize);

$result=array_map('unserialize',$uniue);

print_r($result);

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
  • 1
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 20 '20 at 09:48