php树状

来源:互联网 发布:it培训招生计划 编辑:程序博客网 时间:2024/05/16 19:33
$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));
0 0
原创粉丝点击