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

如何将子数组数据归并至对应父数组?PHP实现需求

Here's a cleaned-up version of your code that will produce the exact structure you're looking for. I've fixed redundant queries, corrected structural issues, and aligned the output with your desired JSON format:

<?php
// Fetch all parent categories in a single query (no need to re-fetch inside the loop)
$parents = $this->db->get('dynamic_parent_category')->result_array();

// Iterate over each parent to attach its corresponding subcategories
foreach ($parents as &$parent) {
    // Use CodeIgniter's query builder to get subcategories linked to this parent
    $subcategories = $this->db
        ->where('parent_cat_id', $parent['df_cat_id'])
        ->get('dynamic_sub_category')
        ->result_array();
    
    // Add the subcategories as a 'childData' property directly to the parent object
    $parent['childData'] = $subcategories;
}

// Construct the final response matching your desired output structure
$finalResponse = [
    'status' => 200,
    'message' => 'Success',
    'child' => [
        'Parent' => $parents
    ]
];

return $finalResponse;
?>

Key improvements made:

  1. Eliminated redundant queries: Your original code was re-fetching the same parent category inside the loop (which also used the wrong query variable $query instead of $parentQuery). We now fetch all parents once upfront.
  2. Structured output correctly: Instead of creating a separate array with the typo parnet and child keys, we directly add the childData array to each parent object to match your desired JSON structure.
  3. Safer querying: Used CodeIgniter's query builder methods (where(), get()) instead of concatenating SQL strings, which helps prevent SQL injection vulnerabilities.
  4. Cleaner code flow: The logic is straightforward - get parents, attach their subcategories, wrap in the required response structure.

This code will return exactly the JSON output you provided in your "期望输出结构" section.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:07:30