You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP按不同group_id拆分含重复ID的数据库动态数组

按group_id分组PHP数组的解决方案

这事儿其实挺简单的,既然你的数组已经是按id(也就是你说的group_id)排好序的了,咱们直接遍历处理就行,效率还高。

方法一:基础遍历法(高效直观)

这种方法适合新手理解,一次遍历就能完成分组,时间复杂度O(n):

$sourcearray = [
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 2, 'value' => 'text'],
    ['id' => 3, 'value' => 'text'],
    ['id' => 4, 'value' => 'text'],
    ['id' => 4, 'value' => 'text'],
];

$grouped = [];
$currentId = null;

foreach ($sourcearray as $item) {
    // 遇到新的id时,初始化对应分组
    if ($item['id'] !== $currentId) {
        $currentId = $item['id'];
        $grouped[$currentId] = [];
    }
    // 将当前元素加入对应分组
    $grouped[$currentId][] = $item;
}

// 可选:如果需要把关联数组转为数字索引数组,执行以下代码
// $grouped = array_values($grouped);

print_r($grouped);

运行后会得到以id为键的分组数组,每个键对应一组相同id的元素。

方法二:使用array_reduce(紧凑函数式写法)

如果你喜欢更简洁的函数式编程风格,可以用PHP内置的array_reduce函数:

$sourcearray = [
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 1, 'value' => 'text'],
    ['id' => 2, 'value' => 'text'],
    ['id' => 3, 'value' => 'text'],
    ['id' => 4, 'value' => 'text'],
    ['id' => 4, 'value' => 'text'],
];

$grouped = array_reduce($sourcearray, function ($carry, $item) {
    $id = $item['id'];
    // 若当前id的分组不存在则创建
    if (!isset($carry[$id])) {
        $carry[$id] = [];
    }
    $carry[$id][] = $item;
    return $carry;
}, []);

// 可选:转为数字索引数组
// $grouped = array_values($grouped);

print_r($grouped);

这个方法会逐步迭代原数组,把每个元素归到对应的分组里,代码更紧凑,逻辑同样清晰。

补充说明

因为你的原数组已经按id排序过了,所以这两种方法都能得到连续且有序的分组。就算数组没排序,这两种方法依然有效,只是分组内的元素顺序会和原数组中出现的顺序一致,完全不影响分组结果。

内容的提问来源于stack exchange,提问作者Jacob MC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:05