如何将子数组数据归并至对应父数组?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:
- Eliminated redundant queries: Your original code was re-fetching the same parent category inside the loop (which also used the wrong query variable
$queryinstead of$parentQuery). We now fetch all parents once upfront. - Structured output correctly: Instead of creating a separate array with the typo
parnetandchildkeys, we directly add thechildDataarray to each parent object to match your desired JSON structure. - Safer querying: Used CodeIgniter's query builder methods (
where(),get()) instead of concatenating SQL strings, which helps prevent SQL injection vulnerabilities. - 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
相关产品推荐
相关产品推荐

