php树状
2015-10-25 14:48
676 查看
$data = [ ['self' => 'd', 'parent' => 'c'], ['self' => 'b', 'parent' => 'a'], ['self' => 'c', 'parent' => 'b'], ['self' => 'e', 'parent' => 'a'], ['self' => 'a', 'parent' => null], ['self' => 'f', 'parent' => 'e'], ['self' => 'h', 'parent' => 'g'], ['self' => 'g', 'parent' => 'f'], ['self' => 'h', 'parent' => null], ['self' => 'i', 'parent' => 'h'], ['self' => 'j', 'parent' => 'g'], ]; /** * @param $data 节点 * @param $parent 父节点 * @param string $keySelf 标识字符串 * @param string $keyParent 父节点标识字符串 * @param string $keyChild 子节点标识字符串 * @param null $null 空父节点标识字符串 * @return mixed 节点 */ function parent($data, $parent, $keySelf = 'self', $keyParent = 'parent', $keyChild = 'child', $null = null) { foreach ($data as $key => $value) { if ($value[$keySelf] == $parent[$keyParent]) {//查找到父级 $data[$key][$keyChild][] = $parent;//子级加入到父级child return $data; } elseif (isset($value[$keyChild])) {//未查找到父级,节点存在子级 $data[$key][$keyChild] = parent($value[$keyChild], $parent, $keySelf, $keyParent, $keyChild, $null);//节点的子级中查找父级 } } return $data; } /** * @param $data 节点数组,结构中包括标识(string,唯一,必须),父节点标识(string,非必须),可包含任意其他数据 * @param string $keySelf 标识字符串 * @param string $keyParent 父节点标识字符串 * @param string $keyChild 子节点标识字符串 * @param null $null 空父节点标识字符串 * @return mixed 树状数组 */ function tree($data, $keySelf = 'self', $keyParent = 'parent', $keyChild = 'child', $null = null) { foreach ($data as $key => $value) { if ($value[$keyParent] != $null) {//处理非顶级 $data = parent($data, $value, $keySelf, $keyParent, $keyChild, $null);//查找父级 unset($data[$key]); } } return $data; } var_dump(tree($data));
相关文章推荐
- PHP读写XLS
- PHP页面静态化
- PHP:小数位计算
- php设计模式
- PHP文件加密解密
- php图形处理
- php中cookie和Session的使用
- ShortestPath:Wormholes(POJ 3259)
- PHP 安全
- PHP出现Notice: unserialize() [function.unserialize]: Error at offset问题的解决方案
- 将php分页类YII绑定框架,就需要改变风格的基础
- PHP手册 – 变量和常量
- php的lareval框架配置出错
- 项目里添加smarty功能步骤
- 重写PHP的explode办法
- xml文档PHP查询代码(学习使用)
- Ubuntu14 下安装laravel 空白修改方法
- 编写不受魔术引号影响的php应用
- 解决PhpStorm不能自动提示父类的方法的问题
- Mac OX 10.11 安装XAMPP+cakePHP