實現無限級分類的一種常用方法是使用遞歸。
下面是一個使用遞歸實現無限級分類的示例代碼:
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的子分類,并用遞歸的方式繼續遍歷子分類的子分類,最終構建出一個無限級分類的樹形結構。
這樣,你就可以方便地使用這個樹形結構來展示無限級分類的數據。