PHP无限极分类实现代码示例 - 构建树形结构
用PHP写一段无限极分类的代码如下:
function buildTree($array, $parentId = 0) {
$tree = array();
foreach ($array as $item) {
if ($item['parent_id'] == $parentId) {
$children = buildTree($array, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
// 示例数据
$data = array(
array('id' => 1, 'name' => '分类1', 'parent_id' => 0),
array('id' => 2, 'name' => '分类2', 'parent_id' => 0),
array('id' => 3, 'name' => '分类1-1', 'parent_id' => 1),
array('id' => 4, 'name' => '分类1-2', 'parent_id' => 1),
array('id' => 5, 'name' => '分类1-1-1', 'parent_id' => 3),
array('id' => 6, 'name' => '分类2-1', 'parent_id' => 2),
);
$tree = buildTree($data);
print_r($tree);
上述代码定义了一个buildTree函数,通过递归方式构建了一个无限级别的分类树。示例数据中的每个分类包含id、name和parent_id属性,其中parent_id表示该分类的父级分类的id,根分类的parent_id为0。
最后,调用buildTree函数并传入示例数据,即可得到一个包含所有分类的树形结构。
原文地址: https://www.cveoy.top/t/topic/pT2R 著作权归作者所有。请勿转载和采集!