Home > Article > Backend Development > How to remove duplicates from an array based on specific key-value pairs in PHP?
In PHP, use the array_unique() function to remove duplicates from an array based on specific key-value pairs. When calling the function, pass in the array as a parameter and select the sorting method as the second parameter. This function returns a new array in which duplicates have been removed based on the specified key-value pairs.
How to remove duplicates from an array based on specific key-value pairs in PHP
In PHP, use The array_unique()
function removes duplicates from an array based on specific key-value pairs. This function receives an array as argument and returns a new array in which duplicates have been removed based on the specified key-value pairs.
Usage:
$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);
Output:
Array ( [0] => Array ( [name] => John [age] => 30 ) [1] => Array ( [name] => Mary [age] => 25 ) [2] => Array ( [name] => Bob [age] => 20 ) )
As shown above, array_unique()
According to Key-value pairs ['name', 'age']
Remove duplicates in the array.
Optional parameters:
array_unique()
The second parameter of the function specifies how to compare array elements. The following options are available:
Practical example:
Suppose you have the following array, which contains line items from different orders:
$orders = [ ['id' => 1, 'item_id' => 1, 'quantity' => 2], ['id' => 2, 'item_id' => 2, 'quantity' => 1], ['id' => 3, 'item_id' => 1, 'quantity' => 3], ];
You can use the following code to sort the order based on the order item ID (item_id
) and quantity (quantity
) Remove duplicates:
$uniqueOrders = array_unique($orders, SORT_REGULAR);
This will create a new array $uniqueOrders
with the item_id
and quantity
combination for each order item All are unique.
The above is the detailed content of How to remove duplicates from an array based on specific key-value pairs in PHP?. For more information, please follow other related articles on the PHP Chinese website!