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

如何在WordPress中将自定义文章类型的分类及子分类转为嵌套数组?

Convert Flat WordPress Category Data to Nested Array

Got it, let's turn that flat database result into the nested structure you need. Here's a straightforward PHP solution tailored to your requirements:

Step 1: Sample Flat Data

First, let's assume your database query returns an associative array like this (matches your table):

// This would come from your WordPress DB query
$flatCategories = [
    ['id' => 1, 'name' => 'categoryName', 'parent' => 0],
    ['id' => 2, 'name' => 'Name1', 'parent' => 1],
    ['id' => 3, 'name' => 'Name2', 'parent' => 1],
    // Optional: Add a sub-sub category to test deeper nesting
    ['id' => 4, 'name' => 'SubName1', 'parent' => 2],
];

Step 2: The Conversion Function

This function will take your flat array and build the nested structure recursively:

function buildNestedCategories($flatCategories) {
    // Group categories by their parent ID for fast lookup
    $groupedByParent = [];
    foreach ($flatCategories as $category) {
        $groupedByParent[$category['parent']][] = $category;
    }

    // Recursive helper to build the tree
    $buildTree = function($parentId) use (&$buildTree, $groupedByParent) {
        $children = [];
        
        // Check if this parent has any child categories
        if (isset($groupedByParent[$parentId])) {
            foreach ($groupedByParent[$parentId] as $cat) {
                // Build the child entry, including its own children
                $childEntry = [
                    'id' => $cat['id'],
                    'name' => $cat['name'],
                    'children' => $buildTree($cat['id'])
                ];
                
                // Set children to empty string if there are no kids (per your example)
                if (empty($childEntry['children'])) {
                    $childEntry['children'] = '';
                }
                
                $children[] = $childEntry;
            }
        }
        
        return $children;
    };

    // Start building from top-level categories (parent ID = 0)
    return $buildTree(0);
}

Step 3: Usage & Result

Call the function and output the nested array:

$nestedCategories = buildNestedCategories($flatCategories);
print_r($nestedCategories);

This will produce exactly the structure you want:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => categoryName
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [name] => Name1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 4
                                            [name] => SubName1
                                            [children] => 
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [id] => 3
                            [name] => Name2
                            [children] => 
                        )

                )

        )

)

Notes for WordPress

If you're fetching the data directly via $wpdb, here's a sample query to get the category data in the right format:

global $wpdb;
$flatCategories = $wpdb->get_results(
    "SELECT term_id as id, name, parent 
     FROM {$wpdb->terms} t 
     JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id 
     WHERE tt.taxonomy = 'category'",
    ARRAY_A
);

This query joins the terms and term_taxonomy tables (WordPress's standard category storage) to get all the fields you need.

内容的提问来源于stack exchange,提问作者Pham Anh Thu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:32:27