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

PHP实现扁平数组分组:按非数值元素生成含units子数组的三维数组

解决方案

直接上可运行的PHP代码,处理你的数组分组需求:

$unitsList = ["Aulas Gratuitas","149","151","153","Módulo 0","964","989","Módulo 1","985","1079","1001","1003","Módulo 2","1009"];

$result = [];
$currentGroup = null;

foreach ($unitsList as $item) {
    // 判断当前元素是否为数值(兼容字符串形式的数字)
    if (!is_numeric($item)) {
        // 遇到非数值元素,新建分组
        $currentGroup = [
            'title' => $item,
            'units' => []
        ];
        $result[] = $currentGroup;
    } else {
        // 数值元素,加入当前分组的units数组
        if ($currentGroup !== null) {
            // 找到结果数组中最后一个分组,追加数值
            end($result);
            $key = key($result);
            $result[$key]['units'][] = $item;
        }
    }
}

// 打印结果查看
print_r($result);

代码说明

  • 初始化$result存储最终分组结果,$currentGroup跟踪当前正在构建的分组
  • 遍历数组时,用is_numeric()判断元素类型:
    • 非数值元素:创建新的title+units结构分组,加入结果数组
    • 数值元素:找到结果数组的最后一个分组,将数值追加到它的units子数组中
  • 额外判断$currentGroup !== null,避免数组开头就是数值的异常情况(你的输入不存在这种情况,但代码更健壮)

预期输出

运行后会得到符合要求的三维数组:

Array
(
    [0] => Array
        (
            [title] => Aulas Gratuitas
            [units] => Array
                (
                    [0] => 149
                    [1] => 151
                    [2] => 153
                )

        )

    [1] => Array
        (
            [title] => Módulo 0
            [units] => Array
                (
                    [0] => 964
                    [1] => 989
                )

        )

    [2] => Array
        (
            [title] => Módulo 1
            [units] => Array
                (
                    [0] => 985
                    [1] => 1079
                    [2] => 1001
                    [3] => 1003
                )

        )

    [3] => Array
        (
            [title] => Módulo 2
            [units] => Array
                (
                    [0] => 1009
                )

        )

)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:35:20