我想过滤我的二维数组以消除重复的 customerName 值。当两行或多行包含相同的 customerName 时,应保留差异最小的行。
我有一个像这样的简单数组。
[
['customerName' => "John Dunk", 'customerPhone' => 5555555555, 'Difference' => 125.0],
['customerName' => "John Dunk", 'customerPhone' => 5555555555, 'Difference' => 192.0],
['customerName' => "James Morle", 'customerPhone' => 111111111, 'Difference' => 145.0],
['customerName' => "James Morle", 'customerPhone' => 111111111, 'Difference' => 114.0],
]
但是我想让这个数组像这样。
[
['customerName' => "John Dunk", 'customerPhone' => 5555555555, 'Difference' => 125.0],
['customerName' => "James Morle", 'customerPhone' => 111111111, 'Difference' => 114.0],
]
如果多维数组内部有 2 行或更多行具有相同的“customerName”,则仅保留具有给定 customerName 和最小“差异”值的行(所有其他行应在结果数组中找到)。
一种方法是按
Difference
降序排序,然后在 customerName
上提取并重新索引。这将提取 customerName
中的最后一个,即最低的 Difference
:
array_multisort(array_column($array, 'Difference'), SORT_DESC, $array);
$result = array_column($array, null, 'customerName');
如果需要用整数重新索引:
$result = array_values($result);
如果您想要最高的
Difference
,那么SORT_ASC
。
注重直接性/效率,您应该只需要迭代数组一次(而不是多次)。在迭代时,当遇到新的 customerName 时,声明一个引用变量以供将来比较/操作,并将该引用推送到结果数组中。如果再次遇到 customerName 并且 Difference 值较低,则更新引用中的值 - 这将直接更新结果数组中的值。
代码:(演示)
$result = [];
foreach ($array as $row) {
if (!isset($ref[$row['customerName']])) {
$ref[$row['customerName']] = $row;
$result[] =& $ref[$row['customerName']];
} elseif ($ref[$row['customerName']]['Difference'] > $row['Difference']) {
$ref[$row['customerName']]['customerPhone'] = $row['customerPhone'];
$ref[$row['customerName']]['Difference'] = $row['Difference'];
}
}
var_export($result);