如何使用php递归实现无穷级分类
使用PHP递归实现无穷级分类的步骤以下:
下面是一个示例代码:
function buildTree($categories, $parent_id = 0) {
$tree = array();
foreach ($categories as $category) {
if ($category['parent_id'] == $parent_id) {
$children = buildTree($categories, $category['id']);
if ($children) {
$category['children'] = $children;
}
$tree[] = $category;
}
}
return $tree;
}
// 示例数据
$categories = array(
array('id' => 1, 'parent_id' => 0, 'name' => '分类1'),
array('id' => 2, 'parent_id' => 0, 'name' => '分类2'),
array('id' => 3, 'parent_id' => 1, 'name' => '分类1⑴'),
array('id' => 4, 'parent_id' => 1, 'name' => '分类1⑵'),
array('id' => 5, 'parent_id' => 3, 'name' => '分类1⑴⑴'),
array('id' => 6, 'parent_id' => 2, 'name' => '分类2⑴'),
array('id' => 7, 'parent_id' => 0, 'name' => '分类3'),
);
$result = buildTree($categories);
print_r($result);
运行以上代码将输出递归生成的分类树形结构数组。
TOP