【问题标题】:Build a multi dimensional array from tree从树构建多维数组
【发布时间】:2015-12-05 14:59:53
【问题描述】:

我在 MySQL 数据库中有一些表示树结构的数据,我想将其转换为 JSON。我使用递归函数来读取所有数据,但我不知道如何转换为数组。

这里是递归函数:

public function buildTree($parent, $level) {

    // retrieve all children of $parent
    $results = Department::all()->where('parent_id',$parent);
    // display each child

    foreach($results as $result)
    {

        echo $this->buildTree($result['id'], $level+1);
    }

}

以下是我最后想要的 JSON 结果:

[  
    {  
        "id":1,
        "text":"Root node",
        "children":[  
            {  
                "id":2,
                "text":"Child node 1",
                "children":[  
                    {  
                        "id":4,
                        "text":"hello world",
                        "children":[{"id":5,"text":"hello world2"}]
                    }
                ]
            },
            {  
                "id":3,
                "text":"Child node 2"
            }
        ]
    }
]

Here is the sample data

【问题讨论】:

    标签: php json multidimensional-array jstree


    【解决方案1】:
    public function buildTree($parent, $level) {
        // The array which will be converted to JSON at the end.
        $json_return = array();
    
        // Get the current element's data.
        $results = Department::all()->where('id',$parent);
        $json_return['id'] = $parent;
        $json_return['text'] = $results[0]['text']; // Or however you access the "text" parameter of the end JSON from the database.
    
        // Retrieve all children of $parent
        $results = Department::all()->where('parent_id',$parent);
    
        if (count($results) > 0)
        {
            $json_return['children'] = array();
            foreach($results as $result)
            {
                $json_return['children'][] = $this->buildTree($result['id'], $level+1);
            }
        }
        // Going to assume that $level by default is 0
        if ($level == 0)
        {
            echo json_encode(array($json_return));
        }
        return $json_return;
    }
    

    【讨论】:

    • 现在我可以使用您建议的代码以 json 格式显示数据。非常感谢!
    • 很高兴它帮助了你!如果这解决了问题,您应该将答案标记为“已接受”:)
    猜你喜欢
    • 2014-05-27
    • 2018-05-30
    • 1970-01-01
    • 2023-03-07
    • 2012-08-01
    • 2015-08-06
    • 1970-01-01
    • 2023-03-21
    • 2021-02-13
    相关资源
    最近更新 更多