php无限极分类树实现代码,支持树(分类)排序,支持生成纵向树及横向树。
横向树:无限极子类展示的树。
纵向树:一维数组展示的平行树结构。
具体实现代码如下:
<?php /** * 无限分类树(支持子分类排序) * version:1.4 * author:Veris */ class ClassTree { /** * 分类排序(降序) */ static public function sort($arr, $cols) { //子分类排序 foreach ($arr as $k => &$v) { if (!empty($v['sub'])) { $v['sub'] = self::sort($v['sub'], $cols); } $sort[$k] = $v[$cols]; } if (isset($sort)) array_multisort($sort, SORT_DESC, $arr); return $arr; } /** * 横向分类树 */ static public function hTree($arr, $pid = 0) { foreach ($arr as $k => $v) { if ($v['pid'] == $pid) { $data[$v['id']] = $v; $data[$v['id']]['sub'] = self::hTree($arr, $v['id']); } } return isset($data) ? $data : array(); } /** * 纵向分类树 */ static public function vTree($arr, $pid = 0) { foreach ($arr as $k => $v) { if ($v['pid'] == $pid) { $data[$v['id']] = $v; $data += self::vTree($arr, $v['id']); } } return isset($data) ? $data : array(); } }
使用例子:
<?php include 'ClassTree.class.php'; $arr = array( array('id' => 1, 'pid' => 0, 'name' => '浙江', 'sort' => 0), array('id' => 10, 'pid' => 1, 'name' => '宁波', 'sort' => 0), array('id' => 13, 'pid' => 1, 'name' => '金华', 'sort' => 1), array('id' => 4, 'pid' => 0, 'name' => '上海', 'sort' => 2), array('id' => 5, 'pid' => 4, 'name' => '闵行', 'sort' => 0), array('id' => 6, 'pid' => 10, 'name' => '宁海', 'sort' => 0), ); $arr = ClassTree::sort($arr, 'sort'); $data = ClassTree::vTree($arr); $data2 = ClassTree::hTree($arr); echo '<pre>'; print_r($data); print_r($data2);
返回结果如下:
Array
(
[4] => Array
(
[id] => 4
[pid] => 0
[name] => 上海
[sort] => 2
)
[5] => Array
(
[id] => 5
[pid] => 4
[name] => 闵行
[sort] => 0
)
[1] => Array
(
[id] => 1
[pid] => 0
[name] => 浙江
[sort] => 0
)
[13] => Array
(
[id] => 13
[pid] => 1
[name] => 金华
[sort] => 1
)
[10] => Array
(
[id] => 10
[pid] => 1
[name] => 宁波
[sort] => 0
)
[6] => Array
(
[id] => 6
[pid] => 10
[name] => 宁海
[sort] => 0
)
)
Array
(
[4] => Array
(
[id] => 4
[pid] => 0
[name] => 上海
[sort] => 2
[sub] => Array
(
[5] => Array
(
[id] => 5
[pid] => 4
[name] => 闵行
[sort] => 0
[sub] => Array
(
)
)
)
)
[1] => Array
(
[id] => 1
[pid] => 0
[name] => 浙江
[sort] => 0
[sub] => Array
(
[13] => Array
(
[id] => 13
[pid] => 1
[name] => 金华
[sort] => 1
[sub] => Array
(
)
)
[10] => Array
(
[id] => 10
[pid] => 1
[name] => 宁波
[sort] => 0
[sub] => Array
(
[6] => Array
(
[id] => 6
[pid] => 10
[name] => 宁海
[sort] => 0
[sub] => Array
(
)
)
)
)
)
)
)
本站部分资源来源于网络,仅限用于学习和研究目的,请勿用于其他用途。
如有侵权请发送邮件至1943759704@qq.com删除
码农资源网 » PHP无限分类树,支持子分类排序和纵向树和横向平行树