一維數據數組生成數據樹

/**
  * 一維數據數組生成數據樹
 */
public static function arr2tree($list, $id = 'id', $pid = 'parent_id', $children = 'children')
{
    list($tree, $map) = [[], []];
    foreach ($list as $item) $map[$item[$id]] = $item;
    foreach ($list as $item) if (isset($item[$pid]) && isset($map[$item[$pid]])) {
        $map[$item[$pid]][$children][] = &$map[$item[$id]];
    } else $tree[] = &$map[$item[$id]];
    unset($map);
    return $tree;
}



   /**
     * 數據樹數組層級關係
     */
    public static function tree2option($tree, $level = 0)
    {
        static $list;
        foreach($tree as $val) {
            if(isset($val['son'])) {
                $flag = str_repeat(' ',$level);
                $list[] = ['id' => $val['cat_id'], 'name' => $flag.$val['cat_name']];
                self::tree2option($val['son'], $level+5);
            } else {
                $flag = str_repeat(' ',$level);
                $list[] = ['id' => $val['cat_id'], 'name' => $flag.$val['cat_name']];
            }
        }
        return $list;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章