什么是无限级分类?
无限级分类是一种对商品或信息进行分类的方式,在这种分类方式中,每个分类都可以再次细分出更多的子分类,形成无限的级别
应用场景:
一个电商网站的分类可以是:服装、鞋类、家居用品等,而服装分类下又可以进一步划分成男装、女装、童装等子分类,男装分类下又可以划分成衬衫、T恤、外套等子分类,这样就形成了多层次的无限级分类
在PHP中实现无限级分类可以使用递归的方法来实现。下面是一个简单的示例:
<?php
// 模拟分类数据
$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);