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

按type分组批量排序PHP二维关联数组(每组最多3个)

PHP数组按规则分组交替排序的高效实现

核心思路

  1. 先分组再排序:将原数组按type字段分组,同时对分组按type升序排列,确保后续遍历顺序符合要求。
  2. 分批交替取数:以“每轮从每个分组取最多3个元素”为规则循环,直到所有元素都被取出,直接按顺序拼接结果数组,避免重复遍历筛选。

代码实现

// 原数组示例(可替换为实际的$items)
$items = [
    ['type' => 2, 'text' => 'b1'],
    ['type' => 1, 'text' => 'a1'],
    ['type' => 1, 'text' => 'a2'],
    ['type' => 2, 'text' => 'b2'],
    ['type' => 1, 'text' => 'a3'],
    ['type' => 1, 'text' => 'a4'],
    ['type' => 2, 'text' => 'b3'],
    ['type' => 2, 'text' => 'b4'],
    ['type' => 3, 'text' => 'c1'],
];

// 1. 按type分组,并对分组按type升序排序
$grouped = [];
foreach ($items as $item) {
    $type = $item['type'];
    $grouped[$type][] = $item;
}
ksort($grouped);
$groups = array_values($grouped);

// 2. 分批交替取元素生成结果
$result = [];
$currentIndexes = array_fill(0, count($groups), 0);
$totalItems = array_sum(array_map('count', $groups));

while (count($result) < $totalItems) {
    foreach ($groups as $idx => $group) {
        $start = $currentIndexes[$idx];
        $remaining = count($group) - $start;
        if ($remaining <= 0) {
            continue;
        }
        // 每轮最多取3个
        $take = min(3, $remaining);
        $result = array_merge($result, array_slice($group, $start, $take));
        $currentIndexes[$idx] += $take;
    }
}

// 输出结果
print_r($result);

方案优势

  • 时间复杂度低:分组和取数过程均为线性遍历,整体复杂度为O(n + m log m)(n为原数组元素数,m为不同type的数量),远优于多次循环筛选的低效方案。
  • 逻辑简洁:避免了重复查询、筛选元素的冗余操作,内存占用更可控。
  • 扩展性强:若需要调整每轮取数的数量(比如从3改为其他值),只需修改min()函数中的数字即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:45:00