0

I know you'll probably think this is a dupe question, and that may be the case but nothing I found seems to actually sort my array. I have built my array and the output looks something like this:

Array => [
    [1] => [
        [1] => [
            'foo' => 'bar',
            'foobar' => 'foo'
        ],
        [2] => [
            'foo' => 'bar',
            'foobar' => 'foo'
        ],
        [3] => [
            'foo' => 'bar',
            'foobar' => 'foo'
        ],
        [4] => [
            'foo' => 'foo',
            'foobar' => 'bar'
        ],
        [5] => [
            'foo' => 'foo',
            'foobar' => 'bar'
        ],
        [6] => [
            'foo' => 'foo',
            'foobar' => 'bar'
        ]
    ]
]

I tried getting rid of the dupe subarrays using these two methods:

array_unique($data, SORT_REGULAR);

but nothing changed.

I also tried using:

$data = array_map(
    'unserialize',
    array_unique(array_map('serialize', $data))
);

But that does nothing either. I've also tried foreach'ing my $data array and adding a to a new array like so:

$newData = [];

foreach ($data as $key => $item)
{
    $newData[$key] = array_map(
        'unserialize', array_unique(array_map('serialize', $item))
    );
}

but that only returned one sub array per key. What am I doing wrong?

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • 3
    If you knew it was a duplicate, why didn't you Google it? This is the top result in Google. [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) – Andreas Nov 06 '18 at 10:42
  • eg https://3v4l.org/5pNT4 – Eakethet Nov 06 '18 at 10:44
  • 1
    @Andreas because as I said in my question - the solution didn't work – treyBake Nov 06 '18 at 10:44
  • Seems like the linked answer expects the "leaf" elements to be arrays, not hashes... so the code needs some minimal changes :) – Oerd Nov 06 '18 at 10:45
  • Then you didn't give it enough tries! If you had Google it you would have found the link I posted with 23 answers. Didn't any of them work?! Really?! – Andreas Nov 06 '18 at 10:46
  • @Andreas yes - really – treyBake Nov 06 '18 at 10:47

1 Answers1

2

You could use array_unique($data, SORT_REGULAR); inside array_map:

$result = array_map(function($x) {
    return array_unique($x, SORT_REGULAR);
}, $data);

print_r($result);

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70