下面是一個處理無限層級分類的PHP遞歸函數示例:
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
函數并傳入示例數據后,將會輸出一個包含層級關系的分類樹。您可以根據實際需求修改示例數據和函數邏輯。