我需要删除数组中的重复项,但它们并不完全重复(所以我不能使用array_unique)。实际上我需要忽略'重复检查'中的一个字段。在下面的示例中,我希望在检查中忽略“RecipientEmail”,因此我应删除第三个元素:
Array
(
[0] => Array
(
[RecipientID] => 1
[RecipientScreenname] => Lau T
[RecipientFirstname] => TK
[RecipientEmail] => lau@xx.co.uk
)
[1] => Array
(
[RecipientID] => 3
[RecipientScreenname] => Tom L
[RecipientFirstname] => Thomas
[RecipientEmail] => info@xx.com
)
[2] => Array
(
[RecipientID] => 1
[RecipientScreenname] => Lau T
[RecipientFirstname] => TK
[RecipientEmail] => other@xx.co.uk
)
)
有没有办法使用任何本机PHP函数?
答案 0 :(得分:2)
一行解决方案没有循环:
array_filter($list, function($el) use(&$unique) { return isset($unique[$key = "{$el['RecipientID']}-{$el['RecipientScreenname']}-{$el['RecipientFirstname']}"]) ? 0 : ($unique[$key] = 1); });
相同但格式化:
array_filter(
$list,
function ($el) use (&$unique) {
return isset($unique[$key = "{$el['RecipientID']}-{$el['RecipientScreenname']}-{$el['RecipientFirstname']}"]) ? 0 : ($unique[$key] = 1);
}
);
答案 1 :(得分:1)
只需在RecipientID
上重新编制索引即可获得一个。如果你需要第一个使用它,如果你需要最后一个,那么使用array_reverse($array)
:
$result = array_column($array, null, 'RecipientID');
如果RecipientID
不能用于唯一性,那么您可以使用值构建密钥。再次,使用此或array_reverse($array)
:
foreach($array as $v) {
$result[$v['RecipientID'].'-'
.$v['RecipientScreenname'].'-'
.$v['RecipientFirstname']
] = $v;
}
如果需要,请$result = array_values($result)
。
答案 2 :(得分:1)
我为你写了一个函数。看看是否有效:
function make_unique($input, $ignore_column)
{
$input = array_reverse($input);
$orig = $input;
array_walk($input, function (&$v) use ($ignore_column) {
unset($v[$ignore_column]);
});
foreach($orig as $index =>$val)
{
unset($input[$index]);
unset($val[$ignore_column]);
if(in_array($val, $input))
unset($orig[$index]);
}
return(array_reverse($orig));
}
var_dump($input);
var_dump(make_unique($input, 'RecipientEmail'));
尝试使用以下输入:
$input =[
[
'RecipientID' => '1',
'RecipientScreenname' => 'Lau T',
'RecipientFirstname' => 'TK',
'RecipientEmail' => 'lau@xx.co.uk'
],
[
'RecipientID' => '2',
'RecipientScreenname' => 'Tom hanks L',
'RecipientFirstname' => 'Thomas',
'RecipientEmail' => 'info@xx.com',
],
[
'RecipientID' => '3',
'RecipientScreenname' => 'Tom L',
'RecipientFirstname' => 'Thomas',
'RecipientEmail' => 'info@xx.com',
],
[
'RecipientID' => '4',
'RecipientScreenname' => '444',
'RecipientFirstname' => 'Thomas',
'RecipientEmail' => 'info@xx.com',
],
[
'RecipientID' => '2',
'RecipientScreenname' => 'Tom hanks L',
'RecipientFirstname' => 'Thomas',
'RecipientEmail' => 'infsdfsdfo@xx.com',
],
[
'RecipientID' => '1',
'RecipientScreenname' => 'Lau T',
'RecipientFirstname' => 'TK',
'RecipientEmail' => 'other@xx.co.uk',
]
];