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

Magento 2.2.3:如何通过REST API将三级分类存储至数组

Extract Level 3 Categories from Magento 2.2.3 REST API Response

Hey there! Let's figure out how to pull all those level 3 categories from your Magento 2.2.3 REST API response into an array. I'll share a couple of approaches depending on your needs—starting with a straightforward one tailored to your specific category structure, then a more flexible recursive method just in case things change later.

Approach 1: Direct Loop (Perfect for Your Current Structure)

Since your category tree follows a clear 1→2→3 level hierarchy, a simple nested loop will do the trick. Here's how to implement this in PHP (the standard language for Magento development):

// First, decode your JSON API response into an associative array
$categoryTreeJson = '{ "id": 2, "parent_id": 1, "name": "Only Beauty", "is_active": true, "position": 1, "level": 1, "product_count": 0, "children_data": [ { "id": 1372323, "parent_id": 2, "name": "Cura della Pelle", "is_active": true, "position": 1, "level": 2, "product_count": 0, "children_data": [ { "id": 1372335, "parent_id": 1372323, "name": "Creme Idratanti Viso", "is_active": true, "position": 1, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1372377, "parent_id": 1372323, "name": "Taglie da Viaggio", "is_active": true, "position": 2, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1372535, "parent_id": 1372323, "name": "Detergenti Viso", "is_active": true, "position": 3, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375522, "parent_id": 1372323, "name": "Struccanti", "is_active": true, "position": 4, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375540, "parent_id": 1372323, "name": "Altri Prodotti per la Pelle", "is_active": true, "position": 5, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375649, "parent_id": 1372323, "name": "Esfolianti & Scrubs", "is_active": true, "position": 6, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375716, "parent_id": 1372323, "name": "Anti-Età", "is_active": true, "position": 7, "level": 3, "product_count": 0, "children_data": [] } ] } ] }';
$categoryTree = json_decode($categoryTreeJson, true);

// Initialize an empty array to store your level 3 categories
$level3Categories = [];

// Loop through level 2 categories (children of the top-level category)
foreach ($categoryTree['children_data'] as $level2Category) {
    // Loop through their children (these are your level 3 categories)
    foreach ($level2Category['children_data'] as $level3Category) {
        // Add the fields you care about to the array (adjust as needed)
        $level3Categories[] = [
            'id' => $level3Category['id'],
            'name' => $level3Category['name'],
            'parent_id' => $level3Category['parent_id'],
            'product_count' => $level3Category['product_count']
        ];
    }
}

// Output the result to verify
print_r($level3Categories);

If you're working with JavaScript instead (e.g., for a frontend integration), here's the equivalent:

// Parse the JSON response into an object
const categoryTree = JSON.parse('{ "id": 2, "parent_id": 1, "name": "Only Beauty", "is_active": true, "position": 1, "level": 1, "product_count": 0, "children_data": [ { "id": 1372323, "parent_id": 2, "name": "Cura della Pelle", "is_active": true, "position": 1, "level": 2, "product_count": 0, "children_data": [ { "id": 1372335, "parent_id": 1372323, "name": "Creme Idratanti Viso", "is_active": true, "position": 1, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1372377, "parent_id": 1372323, "name": "Taglie da Viaggio", "is_active": true, "position": 2, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1372535, "parent_id": 1372323, "name": "Detergenti Viso", "is_active": true, "position": 3, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375522, "parent_id": 1372323, "name": "Struccanti", "is_active": true, "position": 4, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375540, "parent_id": 1372323, "name": "Altri Prodotti per la Pelle", "is_active": true, "position": 5, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375649, "parent_id": 1372323, "name": "Esfolianti & Scrubs", "is_active": true, "position": 6, "level": 3, "product_count": 0, "children_data": [] }, { "id": 1375716, "parent_id": 1372323, "name": "Anti-Età", "is_active": true, "position": 7, "level": 3, "product_count": 0, "children_data": [] } ] } ] }');

// Array to hold level 3 categories
const level3Categories = [];

// Iterate through level 2 and their children
categoryTree.children_data.forEach(level2Cat => {
    level2Cat.children_data.forEach(level3Cat => {
        level3Categories.push({
            id: level3Cat.id,
            name: level3Cat.name,
            parent_id: level3Cat.parent_id,
            product_count: level3Cat.product_count
        });
    });
});

// Check the result in console
console.log(level3Categories);

Approach 2: Recursive Function (Flexible for Future Changes)

If you ever add deeper categories or want to extract other levels easily, a recursive function is a better fit. This will work regardless of how many levels your category tree has:

function extractCategoriesByLevel($category, $targetLevel, $currentLevel = 1, &$result) {
    // If we've reached the target level, add the category to our result
    if ($currentLevel === $targetLevel) {
        $result[] = [
            'id' => $category['id'],
            'name' => $category['name'],
            'parent_id' => $category['parent_id'],
            'product_count' => $category['product_count']
        ];
        return;
    }

    // If there are child categories, recurse into them
    if (!empty($category['children_data'])) {
        foreach ($category['children_data'] as $childCategory) {
            extractCategoriesByLevel($childCategory, $targetLevel, $currentLevel + 1, $result);
        }
    }
}

// Initialize the result array
$level3Categories = [];
// Call the function, targeting level 3
extractCategoriesByLevel($categoryTree, 3, 1, $level3Categories);

// View the output
print_r($level3Categories);

This function will traverse the entire category tree and collect every category that matches your target level (in this case, 3). It's super handy if your category structure evolves over time!

内容的提问来源于stack exchange,提问作者Enrico Nry Celone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:00:45