PHP 陣列轉樹結構/樹結構轉陣列

lixuefeng發表於2021-02-23
public function index()
    {
        $data = [
            [
                'id'=>1,
                'parent_id' => 0,
                'name' => '第一個'
            ],

            [
                'id'=>2,
                'parent_id' => 0,
                'name' => '第二個'
            ],

            [
                'id'=>3,
                'parent_id' => 1,
                'name' => '第三個'
            ],

        ];
        $r = $this->list_to_tree($data);
        dump($r);
    }

Laravel

#陣列轉樹結構#

function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $child = 'children')
{
    // 建立Tree
    $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 = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string)$root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

#樹結構轉陣列#

function tree_to_list($tree = [], $children = 'children')
{
    if (empty($tree) || !is_array($tree)) {
        return $tree;
    }
    $arrRes = [];
    foreach ($tree as $k => $v) {
        $arrTmp = $v;
        unset($arrTmp[$children]);
        $arrRes[] = $arrTmp;
        if (!empty($v[$children])) {
            $arrTmp = tree_to_list($v[$children]);
            $arrRes = array_merge($arrRes, $arrTmp);
        }
    }
    return $arrRes;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章