过滤二维数组以仅保留每个唯一 id 列值的特定列中具有最低值的行

问题描述 投票:0回答:2

我想过滤我的二维数组以消除重复的 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 和最小“差异”值的行(所有其他行应在结果数组中找到)。

php arrays multidimensional-array duplicates filtering
2个回答
0
投票

一种方法是按

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


0
投票

注重直接性/效率,您应该只需要迭代数组一次(而不是多次)。在迭代时,当遇到新的 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);
© www.soinside.com 2019 - 2024. All rights reserved.