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

PHP如何根据header键对动态数组进行切片拆分

实现方案

单次遍历原数组即可完成动态拆分,适配任意长度和header分布的数组,性能更优:

<?php
$arr = [
    ["type" => "header"],
    ["type" => "input"],
    ["type" => "select"],
    ["type" => "header"],
    ["type" => "date"],
    ["type" => "number"],
    ["type" => "text"],
    ["type" => "header"],
    ["type" => "input"],
    ["type" => "input"],
    ["type" => "date"],
    ["type" => "paragraph 1"],
    ["type" => "paragraph 2"],
    ["type" => "paragraph 10546"],
];

$result = [];
$currentGroup = [];

foreach ($arr as $item) {
    if ($item['type'] === 'header') {
        // 遇到header标记,将已收集的非header元素作为分组存入结果
        if (!empty($currentGroup)) {
            $result[] = $currentGroup;
            $currentGroup = [];
        }
        continue;
    }
    // 收集非header元素到当前分组
    $currentGroup[] = $item;
}
// 存入最后一个header后的剩余元素
if (!empty($currentGroup)) {
    $result[] = $currentGroup;
}

// 输出验证
foreach ($result as $group) {
    print_r($group);
}
?>

错误原因说明

原有代码过滤header后得到的新数组索引和原数组索引已不匹配,仍用原数组中header的位置作为切片偏移,导致切片结果不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:24:02