PHP數組轉爲樹的算法

1、使用引用算法

function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    $tree = array(); 
    if (is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[ $data[ $pk ] ] = &$list[ $key ];
        }

        foreach ($list as $key => $data) {
            // 判斷是否存在parent
            $parentId = $data[ $pid ];

            if ($root == $parentId) {
                $tree[ $data[ $pk ] ] = &$list[ $key ];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[ $parentId ];
                    $parent[ $child ][ $data[ $pk ] ] = &$list[ $key ];
                }
            }
        }
    }

    return $tree;
}

 

2、直接循環排列(這個算法沒引用,簡單比較好理解,可是不足是,改變了數據的原始排序)spa

function list_to_tree2($arr, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0){
    foreach($arr as $key => $data){
        $arr[ $data[ $pk ] ] = $data;
        if( $key != $data[ $pk ] ){
            unset($arr[$key]);
        }
    }
    $ids = array_keys($arr);
    arsort($ids); 
    foreach($ids as $key => $id){ 
        if( in_array($arr[ $id ][ $pid ], $ids) ){
            unset($ids[$key]); 
            $arr[ $arr[ $id ][ $pid ] ][ $child ][ $arr[ $id ][ $pk ] ] = $arr[ $id ];
            unset($arr[ $id ]);
        }
    }
 
    return $arr;
}
相關文章
相關標籤/搜索