在 php 中,使用 array_unique() 函数,根据特定键值对去除数组重复项。调用函数时传入数组作为参数,选择排序方式作为第二个参数。此函数返回一个新数组,其中重复项已根据指定的键值对被移除。

如何在 PHP 中根据特定键值对去除数组中的重复项
在 PHP 中,使用 array_unique() 函数可以根据特定键值对去除数组中的重复项。该函数接收一个数组作为参数,并返回一个新数组,其中重复项已根据指定的键值对被移除。
用法:
立即学习“PHP免费学习笔记(深入)”;
$array = [
['name' => 'John', 'age' => 30],
['name' => 'Mary', 'age' => 25],
['name' => 'John', 'age' => 30],
['name' => 'Bob', 'age' => 20],
];
$uniqueArray = array_unique($array, SORT_REGULAR);
print_r($uniqueArray);输出:
Array
(
[0] => Array
(
[name] => John
[age] => 30
)
[1] => Array
(
[name] => Mary
[age] => 25
)
[2] => Array
(
[name] => Bob
[age] => 20
)
)如上所示,array_unique() 根据键值对 ['name', 'age'] 去除了数组中的重复项。
可选参数:
array_unique() 函数的第二个参数指定如何比较数组元素,有以下选项:
实战案例:
假设你有以下数组,其中包含来自不同订单的订单项:
$orders = [
['id' => 1, 'item_id' => 1, 'quantity' => 2],
['id' => 2, 'item_id' => 2, 'quantity' => 1],
['id' => 3, 'item_id' => 1, 'quantity' => 3],
];你可以使用以下代码根据订单项ID (item_id) 和数量 (quantity) 去除重复项:
$uniqueOrders = array_unique($orders, SORT_REGULAR);
这将创建一个新数组 $uniqueOrders,其中每个订单项的 item_id 和 quantity 组合都是唯一的。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号