PHP一維陣列要移除重複的內容,很簡單只要使用array_unique函式即可
例如 :
$input = array("green", "red", "green", "blue", "red");
$result = array_unique($input);
結果$result內容為array( "green", "red", "blue");
二維的key-value陣列要根據特定欄位內容移除重複,要如何處理?
下面是多維(key-value)陣列 :
items[0][“fieldname1”] = …;
items[0][“fieldname2”] = …;
items[0][“fieldname3”] = …;
items[0][“fieldname4”] = …;
…
items[0][“fieldnamen”] = …;
items[1][“fieldname1”] = …;
items[1][“fieldname2”] = …;
items[1][“fieldname3”] = …;
items[1][“fieldname4”] = …;
…
items[1][“fieldnamen”] = …;
….
要去除上面陣列 fieldname1, fieldname2, fieldname3欄位內容相同的item, 程式如下 :
$new_items = array();
$keys = array();
if(!empty($items)) {
foreach($items as $key => $rec) {
$reckey = array($rec["fieldname1"],$rec["fieldname2"],$rec["fieldname3"]);
if(!in_array($reckey,$keys)) {
$keys[] = $reckey;
$new_items[] = $rec;
}
}
}
$items = $new_items;