一、核心类 PHPTreeController.class.php
<?php
/**
* 归属于:Common
* 本类名:PHPTree
* 创建者:IntelliJ IDEA
* 创建时:2021/10/22 00:43:44
* 职责集:PHP生成树形结构,无限多级分类
*/
namespace Common\Controller;
class PHPTreeController
{
protected static $config = array(
/* 主键 */
'primary_key' => 'gc_id',
/* 父键 */
'parent_key' => 'gc_parent_id',
/* 展开属性 */
'expanded_key' => 'expanded',
/* 叶子节点属性 */
'leaf_key' => 'leaf',
/* 孩子节点属性 */
'children_key' => 'children',
/* 是否展开子节点 */
'expanded' => false
);
/* 结果集 */
protected static $result = array();
/* 层次暂存 */
protected static $level = array();
/**
* @name 生成树形结构
* @param array 二维数组
* @return mixed 多维数组
*/
public static function makeTree($data, $options = array())
{
$dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0, $dataset, 'normal');
return $r;
}
/* 生成线性结构, 便于HTML输出, 参数同上 */
public static function makeTreeForHtml($data, $options = array())
{
$dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0, $dataset, 'linear');
return $r;
}
/* 格式化数据, 私有方法 */
private static function buildData($data, $options)
{
$config = array_merge(self::$config, $options);
self::$config = $config;
extract($config);
$r = array();
foreach ($data as $item) {
$id = $item[$primary_key];
$parent_id = $item[$parent_key];
$r[$parent_id][$id] = $item;
}
return $r;
}
/* 生成树核心, 私有方法 */
private static function makeTreeCore($index, $data, $type = 'linear')
{
extract(self::$config);
foreach ($data[$index] as $id => $item) {
if ($type == 'normal') {
if (isset($data[$id])) {
$item[$expanded_key] = self::$config['expanded'];
$item[$children_key] = self::makeTreeCore($id, $data, $type);
} else {
$item[$leaf_key] = true;
}
$r[] = $item;
} else if ($type == 'linear') {
$parent_id = $item[$parent_key];
self::$level[$id] = $index == 0 ? 0 : self::$level[$parent_id] + 1;
$item['level'] = self::$level[$id];
self::$result[] = $item;
if (isset($data[$id])) {
self::makeTreeCore($id, $data, $type);
}
$r = self::$result;
}
}
return $r;
}
}
?>
二、调用方式
这里面的数据结构只要和核心类里面的关键字段对应就行,如果您做的更易用,那就在使用核心类之前,实例化它,并赋予相应的字段配置
public function lst(){
//查询全部数据
$allData = $mdlGoodsClass->where(array('show_type' => 1))->order('gc_parent_id asc,gc_sort asc,gc_id asc')->select();
//处理结构
$result = PHPTreeController::makeTree($allData);
return $result;//这是自己的业务逻辑,你可以直接返回响应
}
有些时候,无限极分类还是必不可少的,应用场景还是有的,希望有所帮助