1
function getCategoryTree($categories, $parent_id = 0) {
$tree = array();
foreach ($categories as $category) {
if ($category['parent_id'] == $parent_id) {
$children = getCategoryTree($categories, $category['id']);
if ($children) {
$category['children'] = $children;
}
$tree[] = $category;
}
}
return $tree;
}
// 示例数据
$categories = array(
array('id' => 1, 'name' => 'Category 1', 'parent_id' => 0),
array('id' => 2, 'name' => 'Category 2', 'parent_id' => 0),
array('id' => 3, 'name' => 'Category 1.1', 'parent_id' => 1),
array('id' => 4, 'name' => 'Category 1.2', 'parent_id' => 1),
array('id' => 5, 'name' => 'Category 1.1.1', 'parent_id' => 3),
);
$tree = getCategoryTree($categories);
print_r($tree);
在上面的例子中,getCategoryTree
函数接受一个包含所有分类的数组和一个父分类ID作为参数,并递归地构建一个树形结构的数组。通过调用getCategoryTree
函数并传入示例数据后,将会输出一个包含层级关系的分类树。您可以根据实际需求修改示例数据和函数逻辑。
2
// 模拟分类数据
$categories = array(
array('id' => 1, 'name' => '电子产品', 'parent_id' => 0),
array('id' => 2, 'name' => '手机', 'parent_id' => 1),
array('id' => 3, 'name' => '笔记本电脑', 'parent_id' => 1),
array('id' => 4, 'name' => '家用电器', 'parent_id' => 0),
array('id' => 5, 'name' => '电视', 'parent_id' => 4),
array('id' => 6, 'name' => '冰箱', 'parent_id' => 4),
array('id' => 7, 'name' => '空调', 'parent_id' => 4),
array('id' => 8, 'name' => '服饰', 'parent_id' => 0),
array('id' => 9, 'name' => '男装', 'parent_id' => 8),
array('id' => 10, 'name' => '女装', 'parent_id' => 8),
array('id' => 11, 'name' => '鞋类', 'parent_id' => 0),
array('id' => 12, 'name' => '男鞋', 'parent_id' => 11),
array('id' => 13, 'name' => '女鞋', 'parent_id' => 11),
array('id' => 14, 'name' => '数码产品', 'parent_id' => 1),
array('id' => 15, 'name' => '相机', 'parent_id' => 14),
array('id' => 16, 'name' => '摄像机', 'parent_id' => 14),
array('id' => 17, 'name' => '办公用品', 'parent_id' => 0),
array('id' => 18, 'name' => '文具', 'parent_id' => 17),
array('id' => 19, 'name' => '办公设备', 'parent_id' => 17),
array('id' => 20, 'name' => '电脑配件', 'parent_id' => 1),
array('id' => 21, 'name' => '显示器', 'parent_id' => 20),
array('id' => 22, 'name' => '内存条', 'parent_id' => 20),
array('id' => 23, 'name' => '游戏机', 'parent_id' => 1),
array('id' => 24, 'name' => 'PS5', 'parent_id' => 23),
array('id' => 25, 'name' => 'Switch', 'parent_id' => 23),
);
// 递归处理分类数据
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;
}
// 构建树形结构
$tree = buildTree($categories);
// 显示分类数据
function showTree($tree, $indent = 0) {
foreach ($tree as $category) {
echo str_repeat("--", $indent) . $category['name'] . "<br>";
if (isset($category['children'])) {
showTree($category['children'], $indent + 1);
}
}
}
// 调用函数显示树形结构
showTree($tree);</pre></div>