簡體   English   中英

從平面數組創建樹

[英]Create a tree from a flat array

我在將平面數組(例如從數據庫查詢)轉換為樹結構時遇到問題。 我有這樣的事情:

[
  [ 
    id => 11,
    path => '/11',
    label => 'AAA'
  ],
  [ 
    id => 12,
    path => '/12',
    label => 'BBB'
  ],
  [ 
    id => 21,
    path => '/12/21',
    label => 'BBBB'
  ],
  [ 
    id => 21,
    path => '/12/22',
    label => 'CCCCC'
  ],
]

path指向樹內的分層 position,由 id 定義。 所以最后我必須得到這樣的東西:

$tree=[
        [
            'id' => '11',
            'label' =>  'AAA'
        ],
        [
            'id' => '12',
            'label' =>  'BBB',
            'children' => [
                [
                    'id' => '21',
                    'label' =>  'BBBB'
                ],
                [
                    'id' => '22',
                    'label' =>  'CCCCC'
                ]
            ]
        ]
    ];

深度可以是無限的。 我將不勝感激任何解決方案。 謝謝:-)

謝謝大家,但我仍然卡住了:-(到目前為止,這是我的方式。

首先,我按深度排序類別並按此順序循環它們。 這樣我可以確定父節點存在。

    public function buildCategoryTree() {
        // order by depth
        $categoryLevel = [];
        foreach (Category::all() as $category) {
            $catPathSplitted = array_filter(explode("/", $category->path));
            $categoryLevel[count($catPathSplitted)][] = $category;
        }

        $categoryTree = [];

        // now loop each level and create a tree node
        foreach ($categoryLevel as $level => $categories) {
            foreach ($categories as $category) {
                $test = $category->path;
                $catPathSplitted = array_filter(explode("/", $category->path));
                $categoryTree = $this->addNode($category, $catPathSplitted, $categoryTree, $test);
            }
        }        
    } 

然后我嘗試使用此遞歸,但它僅部分起作用,這意味着我按層次順序獲取子節點,但子節點也在每個級別上再次創建。 所以有問題:-(

    private function addNode($cat, $keys, &$tree) {
        foreach ($keys as $counter => $id) {
            if (!next($keys)) {
                if (!isset($tree[$id]['category'])) {
                    $tree[$id]['category'] = $cat->toArray();
                }
            } else {
                if (!isset($tree[$id]['children'])) {
                    $tree[$id]['children'] = [];
                }
                array_shift($keys);
                $this->addNode($cat, $keys, $tree[$id]['children'], $test);

            }
        }
        return $tree;
    }

任何人都可以發現缺陷嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM