如何在WordPress中将自定义文章类型的分类及子分类转为嵌套数组?
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

