-1

I have an array as such:

$fake_categories = [
    [
        'handle' => 'food',
        'nice_name' => 'Food'
    ],
    [
        'handle' => 'travel',
        'nice_name' => 'Travel'
    ],
    [
        'handle' => 'fashion',
        'nice_name' => 'Fashion'
    ],
    [
        'handle' => 'food',
        'nice_name' => 'Food'
    ]
];

And I wish to make sure that the packages are unique (by the key handle). As you can see, the last item in the array is a duplicate and needs to be removed.

How can I perform a deep array_unique?

coolpasta
  • 725
  • 5
  • 19

2 Answers2

1

If you want to compare the entire sub-array use @lovelace comment with array-unique with the SORT_REGULAR flag as:

$unique = array_unique($fake_categories, SORT_REGULAR);

If you just want the 'handle' to be unique use array_column to put it as key (which promise handle to be unique) as then array_values to remove the keys as:

$unique = array_values(array_column($fake_categories, null, 'handle'));

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
0

Yes, @lovelace reply is correct. You can use it for your array

<pre>
$fake_categories = [
    [
        'handle' => 'food',
        'nice_name' => 'Food'
    ],
    [
        'handle' => 'travel',
        'nice_name' => 'Travel'
    ],
    [
        'handle' => 'fashion',
        'nice_name' => 'Fashion'
    ],
    [
        'handle' => 'food',
        'nice_name' => 'Food'
    ]
];

    $unique = array_unique( $fake_categories, SORT_REGULAR );
    echo '<pre>';
    print_r($unique);
    echo '</pre>';
</pre>

which will generate output like this:
<pre>
Array
(
    [0] => Array
        (
            [handle] => food
            [nice_name] => Food
        )

    [1] => Array
        (
            [handle] => travel
            [nice_name] => Travel
        )

    [2] => Array
        (
            [handle] => fashion
            [nice_name] => Fashion
        )

)
</pre>