如何确保数组对在 PHP 中是唯一的?



我有一个这样的数组:

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

我希望确保软件包是唯一的(通过键handle(。如您所见,数组中的最后一项是重复项,需要删除。

如何进行深度array_unique

如果要比较整个子数组,请使用@lovelace注释,数组唯一,SORT_REGULAR标志为:

$unique = array_unique($fake_categories, SORT_REGULAR);

如果您只是希望"句柄">是唯一的,请使用array_column将其作为键(承诺handle是唯一的(,然后array_values删除键作为:

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

现场示例:3v4l

是的,@lovelace回复是正确的。您可以将其用于您的阵列

<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>

最新更新