在 php 中,使用 array_unique() 函數(shù),根據(jù)特定鍵值對去除數(shù)組重復(fù)項(xiàng)。調(diào)用函數(shù)時(shí)傳入數(shù)組作為參數(shù),選擇排序方式作為第二個(gè)參數(shù)。此函數(shù)返回一個(gè)新數(shù)組,其中重復(fù)項(xiàng)已根據(jù)指定的鍵值對被移除。
如何在 PHP 中根據(jù)特定鍵值對去除數(shù)組中的重復(fù)項(xiàng)
在 PHP 中,使用 array_unique()
函數(shù)可以根據(jù)特定鍵值對去除數(shù)組中的重復(fù)項(xiàng)。該函數(shù)接收一個(gè)數(shù)組作為參數(shù),并返回一個(gè)新數(shù)組,其中重復(fù)項(xiàng)已根據(jù)指定的鍵值對被移除。
用法:
$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);
登錄后復(fù)制
輸出:
Array ( [0] => Array ( [name] => John [age] => 30 ) [1] => Array ( [name] => Mary [age] => 25 ) [2] => Array ( [name] => Bob [age] => 20 ) )
登錄后復(fù)制
如上所示,array_unique()
根據(jù)鍵值對 ['name', 'age']
去除了數(shù)組中的重復(fù)項(xiàng)。
可選參數(shù):
array_unique()
函數(shù)的第二個(gè)參數(shù)指定如何比較數(shù)組元素,有以下選項(xiàng):
SORT_REGULAR: 正常比較元素SORT_NUMERIC: 比較元素作為數(shù)字SORT_STRING: 比較元素作為字符串SORT_LOCALE_STRING: 以特定區(qū)域設(shè)置比較元素作為字符串
實(shí)戰(zhàn)案例:
假設(shè)你有以下數(shù)組,其中包含來自不同訂單的訂單項(xiàng):
$orders = [ ['id' => 1, 'item_id' => 1, 'quantity' => 2], ['id' => 2, 'item_id' => 2, 'quantity' => 1], ['id' => 3, 'item_id' => 1, 'quantity' => 3], ];
登錄后復(fù)制
你可以使用以下代碼根據(jù)訂單項(xiàng)ID (item_id
) 和數(shù)量 (quantity
) 去除重復(fù)項(xiàng):
$uniqueOrders = array_unique($orders, SORT_REGULAR);
登錄后復(fù)制
這將創(chuàng)建一個(gè)新數(shù)組 $uniqueOrders
,其中每個(gè)訂單項(xiàng)的 item_id
和 quantity
組合都是唯一的。