PHP循环按多分类ID分组生成指定结构JavaScript对象的问题求助
Hey HelmaJS, I totally get where you're stuck here! The issue is that your current PHP loop is creating a new entry in the subkategoris object for every single row in your table—so you're ending up with duplicate category keys (like "1" appearing twice), each holding just one subcategory. Instead, you need to group your subcategories by their parent category ID first before building out the JavaScript code.
Why Your Current Output Is Wrong
Right now, every time you loop through a row, you're printing an entirely new key-value pair for the category. In JavaScript, duplicate object keys are technically allowed but will either overwrite each other or produce invalid-looking output that doesn't behave as expected. You want each category key to map to an array that contains all its subcategories, not just one.
Step-by-Step Solution
Let's break this into two simple parts: grouping your data in PHP, then generating the correct JS structure.
1. Group Your Data by Category
First, take your raw table data and restructure it into a PHP associative array where each key is a category ID, and the value is an array of subcategory items. Here's how:
Assuming you have your data in a PHP array (like you'd retrieve from a database query):
// Sample data matching your table $tableData = [ ['id' => 1, 'category' => 1, 'subcategory' => 'Apple'], ['id' => 2, 'category' => 1, 'subcategory' => 'Orange'], ['id' => 3, 'category' => 2, 'subcategory' => 'Car'], ['id' => 4, 'category' => 2, 'subcategory' => 'Motorcycle'], ]; // Group subcategories by category ID $groupedSubcats = []; foreach ($tableData as $row) { $catId = $row['category']; // Initialize the category array if it doesn't exist yet if (!isset($groupedSubcats[$catId])) { $groupedSubcats[$catId] = []; } // Add the current subcategory to the category's array $groupedSubcats[$catId][] = [ 'value' => $row['id'], 'desc' => $row['subcategory'] ]; }
2. Generate the JavaScript Code
Now loop through the grouped array to build the valid subkategoris object:
// Start the script tag echo '<script type="text/javascript">'; echo 'const subkategoris = {'; // Loop through each grouped category foreach ($groupedSubcats as $catId => $subcats) { echo "\"$catId\":["; // Collect all subcategory strings for this category $subcatEntries = []; foreach ($subcats as $subcat) { $subcatEntries[] = "{value:{$subcat['value']},desc:\"{$subcat['desc']}\"}"; } // Join the subcategory entries with commas echo implode(',', $subcatEntries); echo "],"; } // Close the object and script tag echo '}'; echo '</script>';
Resulting JavaScript
This will output exactly the structure you're looking for:
<script type="text/javascript"> const subkategoris = { "1":[ {value:1,desc:"Apple"},{value:2,desc:"Orange"} ], "2":[ {value:3,desc:"Car"},{value:4,desc:"Motorcycle"} ], } </script>
A quick note: The trailing comma after the last category array is totally fine in modern JavaScript—all major browsers support it. If you need to support older environments, you can add a check to avoid adding the comma for the last category, but it's usually not necessary these days.
内容的提问来源于stack exchange,提问作者HelmaJS

