thinkphp5使用无限极分类
本文实例为大家分享了thinkphp5使用无限极分类的具体代码,供大家参考,具体内容如下
1. 先根据普通递归完成无限极分类
2. 再根据分号的类的level 添加字符,再次存入数组的_name字段,最后按照_name字段输出
/** * 获得树状数据 * @param $data 数据 * @param $title 数据库中字段名 * @param string $fieldPri 数据库中主键id * @param string $fieldPid 数据库中父id * @return array */ static public function tree($data, $title, $fieldPri = 'cid', $fieldPid = 'pid') { if (!is_array($data) || empty($data)) return array(); $arr = Data::channelList($data); foreach ($arr as $k => $v) { $str = ""; if ($v['_level'] > 2) { for ($i = 1; $i < $v['_level'] - 1; $i++) { $str .= "│ "; } } if ($v['_level'] != 1) { $t = $title ? $v[$title] : ""; if (isset($arr[$k + 1]) && $arr[$k + 1]['_level'] >= $arr[$k]['_level']) { $arr[$k]['_name'] = $str . "├─ " . $v['_html'] . $t; } else { $arr[$k]['_name'] = $str . "└─ " . $v['_html'] . $t; } } else { $arr[$k]['_name'] = $v[$title]; } } //设置主键为$fieldPri $data = array(); foreach ($arr as $d) { $data[$d[$fieldPri]] = $d; } return $data; }
/** * 获得所有子栏目 * @param $data 栏目数据 * @param int $pid 操作的栏目 * @param string $html 栏目名前字符 * @param string $fieldPri 表主键 * @param string $fieldPid 父id * @param int $level 等级 * @return array */ static public function channelList($data, $pid = 0, $html = " ", $fieldPri = 'cid', $fieldPid = 'pid', $level = 1) { $data = self::_channelList($data, $pid, $html, $fieldPri, $fieldPid, $level); if (empty($data)) return $data; foreach ($data as $n => $m) { if ($m['_level'] == 1) continue;//结束单次循环 $data[$n]['_first'] = false; $data[$n]['_end'] = false; if (!isset($data[$n - 1]) || $data[$n - 1]['_level'] != $m['_level']) { $data[$n]['_first'] = true; } if (isset($data[$n + 1]) && $data[$n]['_level'] > $data[$n + 1]['_level']) { $data[$n]['_end'] = true; } } //更新key为栏目主键 $category=array(); foreach($data as $d){ $category[$d[$fieldPri]]=$d; } return $category; }
//只供channelList方法使用 /** * 获得所有子栏目 * @param $data 栏目数据 * @param int $pid 操作的栏目 * @param string $html 栏目名前字符 * @param string $fieldPri 表主键 * @param string $fieldPid 父id * @param int $level 等级 * @return array */ static private function _channelList($data, $pid = 0, $html = " ", $fieldPri = 'cid', $fieldPid = 'pid', $level = 1) { if (empty($data)) return array(); $arr = array(); foreach ($data as $v) { $id = $v[$fieldPri]; if ($v[$fieldPid] == $pid) { $v['_level'] = $level; $v['_html'] = str_repeat($html, $level - 1); $arr[] = $v; $tmp = self::_channelList($data, $id, $html, $fieldPri, $fieldPid, $level + 1); $arr = array_merge($arr, $tmp);//array_merge把两个数组整合为一个数组 } } return $arr; }
相关推荐
YClimb 2020-09-15
FellowYourHeart 2020-04-23
K先生 2020-11-10
wushengyong 2020-10-28
FellowYourHeart 2020-10-05
gaosf 2020-06-14
Hesland 2020-06-14
fanfangood 2020-06-14
稳哥的小灶 2020-05-29
小周 2020-04-30
gaosf 2020-04-25
小周 2020-04-25
FellowYourHeart 2020-04-25
稳哥的小灶 2020-04-25
ThinkPHP 2020-03-28
doupoo 2020-01-28