php - 对数据行进行分组,在组内维护一个id的子数组,只呈现每组中最低的id作为一级key

标签 php arrays multidimensional-array merge grouping

我需要将行数组合并到组中,并使用每个组中最低的 id 作为第一级键。在每个组中,所有遇到的 ID(不包括最低的)都应该收集在一个名为 mergedWith 的子数组中。

示例输入:

[
    1649 => ["firstName" => "jack", "lastName" => "straw"],
    1650 => ["firstName" => "jack", "lastName" => "straw"],
    1651 => ["firstName" => "jack", "lastName" => "straw"],
    1652 => ["firstName" => "jack", "lastName" => "straw"],
]

我想要的结果:

[
    1649 => [
        "firstName" => "jack"
        "lastName" => "straw"
        "mergedWith" => [1650, 1651, 1652]
    ]
]

我有一个循环运行,可以提取重复项并找到组中最低的 ID,但不确定将它们合并为一个的正确方法。

我已经显示了搜索的预期结果,该搜索已识别出在这些特定字段中具有重复条目的 ID。我只是想进一步细化它而不是删除,而是在每个组的末尾添加一个字段,上面写着 ["mergedWith"=> [1650, 1651, 1652]]

最佳答案

一种方法是按名字和姓氏分组,然后反转分组以获得单个 ID。 krsort 预先输入以确保您获得最低的 id。

krsort($input);

//group
foreach ($input as $id => $person) {
    // overwrite the id each time, but since the input is sorted by id in descending order,
    // the last one will be the lowest id
    $names[$person['lastName']][$person['firstName']] = $id;
}

// ungroup to get the result
foreach ($names as $lastName => $firstNames) {
    foreach ($firstNames as $firstName => $id) {
        $result[$id] = ['firstName' => $firstName, 'lastName' => $lastName];
    }
}

编辑:根据您更新的问题,差别不大。只保留所有 ID 而不是一个。

krsort($input);

foreach ($input as $id => $person) {
    //                   append instead of overwrite ↓ 
    $names[$person['lastName']][$person['firstName']][] = $id;
}
foreach ($names as $lastName => $firstNames) {
    foreach ($firstNames as $firstName => $ids) {
        // $ids is already in descending order based on the initial krsort
        $id = array_pop($ids);  // removes the last (lowest) id and returns it
        $result[$id] = [
            'firstName' => $firstName,
            'lastName' => $lastName,
            'merged_with' => implode(',', $ids)
        ];
    }
}

关于php - 对数据行进行分组,在组内维护一个id的子数组,只呈现每组中最低的id作为一级key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432803/

相关文章:

php - 使用 Google Translate 在 PHP 中进行文字转语音

php - PHP中的数组求和

复制指针值

php - 层级评论系统php

c - 数组和指针算术~需要澄清

php - 正则表达式可以更快地做到这一点吗?

php - 将数组传递给 web 服务 php nusoap

javascript - 如何在javascript中通过属性删除对象

php未插入mysql

c++ - 冒泡排序功能在数组中途停止工作