[php]運用變數引用實現一維陣列轉多維樹狀陣列

hi.tony發表於2016-05-09
/**
 * 運用 變數引用 實現 一維陣列 轉 多維樹狀陣列
 * @param $array
 * @param array $options = [`id`=>`id`, `pid`=>`pid`, `sub`=>`_sub`, `root`=>0]
 * @return array
 */
public static function array2Tree($array, $options = []) {

    /** merge Options */
    $opt = array_merge([`id`=>`id`, `pid`=>`pid`, `sub`=>`_sub`, `root`=>0], $options);

    $tree = [];

    if(is_array($array)){

        $refer = [];

        foreach ($array as $k => $v) {
            $refer[$v[$opt[`id`]]] =& $array[$k];
        }

        foreach ($array as $k => $v) {

            $parentId = $v[$opt[`pid`]];

            if ($opt[`root`] == $parentId) {

                $tree[$v[$opt[`id`]]] =& $array[$k];

            }else{

                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$opt[`sub`]][$v[$opt[`id`]]] =& $array[$k];
                    unset($array[$k]);
                }
            }
        }
        unset($refer, $array);
    }
    return $tree;
}


相關文章