阅读量:0
PHP无限极分类的方法有多种,下面是其中一种常见的方法:
- 使用递归函数: 首先,构建一个多维数组来表示分类的层级关系。每个分类包含一个id和parent_id,parent_id表示该分类的父级分类id。 然后,编写一个递归函数来遍历该多维数组,根据parent_id将子分类添加到对应的父分类下。可以使用一个空数组来存储最终的无限极分类结果。
以下是一个示例代码:
function buildTree($categories, $parent_id = 0) { $tree = array(); foreach ($categories as $category) { if ($category['parent_id'] == $parent_id) { $children = buildTree($categories, $category['id']); if (!empty($children)) { $category['children'] = $children; } $tree[] = $category; } } return $tree; }
使用示例:
$categories = array( array('id' => 1, 'name' => '分类1', 'parent_id' => 0), array('id' => 2, 'name' => '分类2', 'parent_id' => 0), array('id' => 3, 'name' => '分类3', 'parent_id' => 1), array('id' => 4, 'name' => '分类4', 'parent_id' => 1), array('id' => 5, 'name' => '分类5', 'parent_id' => 2), array('id' => 6, 'name' => '分类6', 'parent_id' => 3), array('id' => 7, 'name' => '分类7', 'parent_id' => 3), ); $tree = buildTree($categories); print_r($tree);
输出结果:
Array ( [0] => Array ( [id] => 1 [name] => 分类1 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 3 [name] => 分类3 [parent_id] => 1 [children] => Array ( [0] => Array ( [id] => 6 [name] => 分类6 [parent_id] => 3 ) [1] => Array ( [id] => 7 [name] => 分类7 [parent_id] => 3 ) ) ) [1] => Array ( [id] => 4 [name] => 分类4 [parent_id] => 1 ) ) ) [1] => Array ( [id] => 2 [name] => 分类2 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 5 [name] => 分类5 [parent_id] => 2 ) ) ) )
这样就可以将多维数组按照层级关系转换成无限极分类。