php 一个无限级分类的开源类库

php 一个无限级分类的开源类库

无限级分类示意图

php程序开发中,经常会用到无限级分类。大家可以自己写递归来解决。

这里推荐一个开源的类库bluem/tree

composer 的地址https://packagist.org/packages/bluem/tree

使用方法:

$tree = new BlueMTree($data);

$data是从数据库查询出来的数据【也可以自己组装数组】

$db = new PDO(...); $stm = $db->query('SELECT id, parent, title FROM tablename ORDER BY title'); $data = $stm->fetchAll(PDO::FETCH_ASSOC);

id----当前分类自身ID

parent----父类ID

title----分类名

下面列出常用的方法

//获取顶级节点 $rootNodes = $tree->getRootNodes(); //得到所有节点 $allNodes = $tree->getNodes(); //通过唯一的标识符获取单个节点 $node = $tree->getNodeById(12345); //获取节点ID $id = $node->getId(); //获取节点的父节点(对于根节点将是NULL) $parentNode = $node->getParent(); / 获得节点的层次 $level = $node->getLevel(); //获取同级的节点 $siblings = $node->getSiblings(); //同上,但包括节点本身 $siblings = $node->getSiblingsAndSelf(); //获取节点的子节点 $children = $node->getChildren(); // 是否有子节点? $bool = $node->hasChildren(); // 子节点个数 $bool = $node->countChildren(); //获取节点的后代(子、孙子、…) $descendants = $node->getDescendants(); // 同上,但包含的自身节点 $descendantsPlusSelf = $node->getDescendantsAndSelf(); // $node 是个对象 这个方法是转成数组 $array = $node->toArray();

有不清楚的可以关注 私信我

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: