• PHP把从数据库查出的数据,根据主键外键,变成关系树(多叉树),从而转成json给前端使用。【递归思想,原创】


    $arr = [
    ['id' => 3, 'pid' => 0, 'name' => 'A'],
    ['id' => 4, 'pid' => 3, 'name' => 'B'],
    ['id' => 5, 'pid' => 3, 'name' => 'C'],
    ['id' => 6, 'pid' => 3, 'name' => 'D'],
    ['id' => 7, 'pid' => 5, 'name' => 'E'],
    ['id' => 8, 'pid' => 4, 'name' => 'F'],
    ['id' => 9, 'pid' => 6, 'name' => 'G'],
    ['id' => 10, 'pid' => 0, 'name' => 'H'],
    ['id' => 11, 'pid' => 9, 'name' => 'I'],
    ['id' => 12, 'pid' => 8, 'name' => 'J'],
    ['id' => 13, 'pid' => 6, 'name' => 'K'],
    ['id' => 14, 'pid' => 10, 'name' => 'L'],
    ['id' => 15, 'pid' => 0, 'name' => 'M'],
    ['id' => 16, 'pid' => 4, 'name' => 'N'],
    ];


    /**
    * @param $arr 传入的数组
    * @param $pid 连接关系参照字段
    * @param $pKey 最终生成关系组的下标
    * @param $tree 返回最终的处理结果
    * @return array
    */
    function ToTree($arr,$pid,$pKey,&$tree){
    $currentDeep = [];
    foreach($arr as $key => $value){
    if($value['pid'] == $pid) { # 有儿子
    $value[$pKey] = ToTree($arr,$value['id'],$pKey,$tree); # 找儿子
    $currentDeep[] = $value;
    }
    }
    if($currentDeep && $pid == 0){ # 当前根节点的儿子都找完了, 把当前根节点的儿子全部归位
    $tree = $currentDeep;
    }
    return $currentDeep;
    }

    $tree = [];
    ToTree($arr,0,'child',$tree);
    #echo json_encode($tree);
    print_r($tree);
    
    
  • 相关阅读:
    初识js中的闭包
    ES5新增数组方法every()、some()、filter()、map()
    arguments对象的callee属性和caller属性
    js中的全局变量
    js中switch/case分支的值可以是变量或表达式
    js中的arguments对象
    CSSの変数を使う
    我应该使用预处理器吗
    JS导出网页数据到EXCEL
    冰与火之歌:浏览器前缀
  • 原文地址:https://www.cnblogs.com/wangshuazi/p/14582678.html
Copyright © 2020-2023  润新知