阅读量:0
实现无限级分类的一种常用方法是使用递归。
下面是一个使用递归实现无限级分类的示例代码:
function buildTree($categories, $parentId = 0) { $tree = array(); foreach ($categories as $category) { if ($category['parent_id'] == $parentId) { $children = buildTree($categories, $category['id']); if ($children) { $category['children'] = $children; } $tree[] = $category; } } return $tree; } // 示例数据 $categories = array( array('id' => 1, 'parent_id' => 0, 'name' => 'Category 1'), array('id' => 2, 'parent_id' => 0, 'name' => 'Category 2'), array('id' => 3, 'parent_id' => 1, 'name' => 'Category 1.1'), array('id' => 4, 'parent_id' => 1, 'name' => 'Category 1.2'), array('id' => 5, 'parent_id' => 3, 'name' => 'Category 1.1.1'), array('id' => 6, 'parent_id' => 2, 'name' => 'Category 2.1'), ); $tree = buildTree($categories); print_r($tree);
输出结果:
Array ( [0] => Array ( [id] => 1 [parent_id] => 0 [name] => Category 1 [children] => Array ( [0] => Array ( [id] => 3 [parent_id] => 1 [name] => Category 1.1 [children] => Array ( [0] => Array ( [id] => 5 [parent_id] => 3 [name] => Category 1.1.1 ) ) ) [1] => Array ( [id] => 4 [parent_id] => 1 [name] => Category 1.2 ) ) ) [1] => Array ( [id] => 2 [parent_id] => 0 [name] => Category 2 [children] => Array ( [0] => Array ( [id] => 6 [parent_id] => 2 [name] => Category 2.1 ) ) ) )
上述代码中,buildTree
函数接收一个包含分类数据的数组和一个指定的父分类ID。它通过遍历分类数组,找到所有指定父分类ID的子分类,并用递归的方式继续遍历子分类的子分类,最终构建出一个无限级分类的树形结构。
这样,你就可以方便地使用这个树形结构来展示无限级分类的数据。