我想删除重复的数组,同时添加一个新的密钥'duplicates'和重复的总数到原始数组。使用PHP执行此操作的最佳方法是什么?
Array
(
[0] => Array
(
[w] => 10
[r] => 10
[e] => 489
)
[1] => Array
(
[w] => 10
[r] => 10
[e] => 489
)
[2] => Array
(
[w] => 10
[r] => 10
[e] => 489
)
[3] => Array
(
[w] => 20
[r] => 20
[e] => 489
)
[4] => Array
(
[w] => 10
[r] => 10
[e] =>
)
)
会变成:
Array
(
[0] => Array
(
[w] => 10
[r] => 10
[e] => 489
[duplicates] => 2
)
[3] => Array
(
[w] => 20
[r] => 20
[e] => 489
)
[4] => Array
(
[w] => 10
[r] => 10
[e] =>
)
)
答案 0 :(得分:0)
您可以获取唯一数组,然后与原始数组进行比较:
$result = array_map("unserialize", array_unique(array_map("serialize", $input)));
foreach ($result as &$arr) {
$cnt = 0;
foreach ($input as $inArr) {
if ($arr == $inArr) {
$cnt++;
}
}
if ($cnt > 1) {
$arr['duplicates'] = $cnt - 1;
}
}