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 (!empty($children)) {
$category['children'] = $children;
}
$tree[] = $category;
}
}
return $tree;
}
使用示例:
$categories = array(
array('id' => 1, 'name' => '分類1', 'parent_id' => 0),
array('id' => 2, 'name' => '分類2', 'parent_id' => 0),
array('id' => 3, 'name' => '分類3', 'parent_id' => 1),
array('id' => 4, 'name' => '分類4', 'parent_id' => 1),
array('id' => 5, 'name' => '分類5', 'parent_id' => 2),
array('id' => 6, 'name' => '分類6', 'parent_id' => 3),
array('id' => 7, 'name' => '分類7', 'parent_id' => 3),
);
$tree = buildTree($categories);
print_r($tree);
輸出結果:
Array
(
[0] => Array
(
[id] => 1
[name] => 分類1
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => 分類3
[parent_id] => 1
[children] => Array
(
[0] => Array
(
[id] => 6
[name] => 分類6
[parent_id] => 3
)
[1] => Array
(
[id] => 7
[name] => 分類7
[parent_id] => 3
)
)
)
[1] => Array
(
[id] => 4
[name] => 分類4
[parent_id] => 1
)
)
)
[1] => Array
(
[id] => 2
[name] => 分類2
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 5
[name] => 分類5
[parent_id] => 2
)
)
)
)
這樣就可以將多維數組按照層級關系轉換成無限極分類。