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
)
)
)
)
这样就可以将多维数组按照层级关系转换成无限极分类。