如果我有这样的数组:
Array (
[0]=>
Array (
["id"]=> "1"
["desc"]=> "desc 1"
["type"]=> "T"
["date"]=> "17-JAN-12"
)
[1]=>
Array (
["id"]=> "2"
["desc"]=> "desc 2"
["type"]=> "P"
["date"]=> "05-JAN-12"
)
[2]=>
Array (
["id"]=> "1"
["desc"]=> "desc 3"
["type"]=> "P"
["date"]=> "15-JAN-12"
)
[3]=>
Array (
["id"]=> "3"
["desc"]=> "desc 4"
["type"]=> "P"
["date"]=> "06-JAN-12"
)
[4]=>
Array (
["id"]=> "2"
["desc"]=> "desc 5"
["type"]=> "T"
["date"]=> "06-JAN-12"
)
)
我想从中删除仅在键“id”上具有重复值的元素, 得到:
Array (
[0]=>
Array (
["id"]=> "1"
["desc"]=> "desc 1"
["type"]=> "T"
["date"]=> "17-JAN-12"
)
[1]=>
Array (
["id"]=> "2"
["desc"]=> "desc 2"
["type"]=> "P"
["date"]=> "05-JAN-12"
)
[2]=>
Array (
["id"]=> "3"
["desc"]=> "desc 4"
["type"]=> "P"
["date"]=> "06-JAN-12"
)
)
感谢。
答案 0 :(得分:6)
$result = array();
foreach($array as $arr){
if(!isset($result[$arr["id"]])){
$result[$arr["id"]] = $arr;
}
}
答案 1 :(得分:2)
似乎id
是您的主要键。所以只有当id
不存在时才循环遍历数组并将元素插入新数组。
$new_array = array();
foreach ($old_array as $entry) {
if (empty($new_array[$entry['id']])) $new_array[$entry['id']] = $entry;
}
$new_array = array_values($new_array);
顺便说一句。最后一行仅用于在最终数组中重新排序键