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

PHP数组分组问题:按父名称聚合数据时items数组被覆盖

解决按父名称分组时items被覆盖的问题

问题根源

当前代码在循环中直接将$option->title赋值给items,每次循环都会覆盖之前的内容,导致每个分组最终只保留最后遍历到的那一项,而非收集同组的所有项。

修正思路

  • 确保每个分组的items是数组类型,而非单个字符串
  • 循环时先判断分组是否已初始化:
    • 未初始化的话,先创建包含对应title和空items数组的结构
    • 已初始化的话,将当前项追加到items数组中

修正后的代码

$result = array();
foreach ($page->products_codes as $option) {
    $parentName = $option->parent->name;
    
    // 初始化分组结构(如果不存在)
    if (!isset($result[$parentName])) {
        $result[$parentName] = [
            "title" => $option->parent->title,
            "items" => []
        ];
    }
    
    // 将当前项追加到items数组,而非覆盖
    $result[$parentName]["items"][] = $option->title;
}

关键修正点

  • 缓存$parentName,避免重复访问对象属性,提升代码效率
  • 用isset()判断分组是否存在,确保items始终是数组
  • 使用[]语法实现数组追加,替代直接赋值的覆盖操作

预期输出示例

修正后同组的多个项会被收集到items数组中:

array (
  'fixture' => 
  array (
    'title' => 'Fixture',
    'items' => array(
      'Pinhole90 Fixed with LED51',
      'Recessed Fixture with LED45'
    ),
  ),
  // 其他分组结构类似
)

内容的提问来源于stack exchange,提问作者John the Painter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:16:14