我需要过滤掉二维数组中的重复行,并在保留的唯一行中附加一个元素,该元素包含原始数组中唯一行存在的次数。
我想使用
array_unique($array, SORT_REGULAR)
,但删除重复项是不够的——我实际上需要存储每个唯一行的重复行数。
我已经尝试过
array_search()
和循环,但我的尝试都没有产生正确的结果。我的项目数据有超过 500,000 个条目,但这是一个基本示例:
输入:
[
['manufacturer' => 'KInd', 'brand' => 'ABC', 'used' => 'true'],
['manufacturer' => 'KInd', 'brand' => 'ABC', 'used' => 'true'],
['manufacturer' => 'KInd', 'brand' => 'ABC', 'used' => 'false'],
]
输出:
[
['manufacturer' => 'KInd', 'brand' => 'ABC', 'used' => 'true', 'count' => 2],
['manufacturer' => 'KInd', 'brand' => 'ABC', 'used' => 'false', 'count' => 1],
]
您不需要使用任何复杂的序列化或编码来创建用于分组的组合键。只需内爆每一行的值(假设它们都包含相同顺序的相同列)来为结果数组创建一个标识键。
第一次遇到时,将行的数据存入组中,并设置组的计数为1;在随后的任何遭遇中,增加该组的计数器。
代码:(演示)
$result = [];
foreach ($array as $row) {
$compositeKey = implode('_', $row);
if (!isset($result[$compositeKey])) {
$result[$compositeKey] = $row + ['count' => 1];
} else {
++$result[$compositeKey]['count'];
}
}
var_export(array_values($result));
输出:
array (
0 =>
array (
'manufacturer' => 'KInd',
'brand' => 'ABC',
'used' => 'true',
'count' => 2,
),
1 =>
array (
'manufacturer' => 'KInd',
'brand' => 'ABC',
'used' => 'false',
'count' => 1,
),
)
其他利用多个标识列值进行分组的帖子:
如果我理解正确,这应该有所帮助
function getUniqWithCounts(array $data): array
{
$result = [];
foreach ($data as $item) {
$hash = md5(serialize($item));
if (isset($result[$hash])) {
$result[$hash]['count']++;
continue;
}
$item['count'] = 1;
$result[$hash] = $item;
}
return array_values($result);
}