将层次结构提取到json中

时间:2017-10-15 08:25:31

标签: php json

我无法将我的mysql表格变成json。 我有一张表格显示员工的层次结构:

该表是一张员工表     id,firstname,lastname,parentid

所以现在我想通过数据查询将其提取到一个多级json对象中来模拟向员工展示他们的主管。

我希望有人能帮助我。

1 个答案:

答案 0 :(得分:0)

假设您已经从数据库中获取了数据,下面的解决方案将为您提供所需的数据。

实现目标的方法是通过递归

php sandbox online

Array
(
    [1] => Array
        (
            [id] => 1
            [firstname] => john1
            [lastname] => doe
            [parentid] => 0
            [children] => Array
                (
                    [2] => Array
                        (
                            [id] => 2
                            [firstname] => john2
                            [lastname] => doe
                            [parentid] => 1
                        )

                    [3] => Array
                        (
                            [id] => 3
                            [firstname] => john3
                            [lastname] => doe
                            [parentid] => 1
                            [children] => Array
                                (
                                    [5] => Array
                                        (
                                            [id] => 5
                                            [firstname] => john5
                                            [lastname] => doe
                                            [parentid] => 3
                                        )

                                )

                        )

                )

        )

    [4] => Array
        (
            [id] => 4
            [firstname] => john4
            [lastname] => doe
            [parentid] => 0
        )

)

和结果数组:

json_encode

在您{ "1": { "id": 1, "firstname": "john1", "lastname": "doe", "parentid": 0, "children": { "2": { "id": 2, "firstname": "john2", "lastname": "doe", "parentid": 1 }, "3": { "id": 3, "firstname": "john3", "lastname": "doe", "parentid": 1, "children": { "5": { "id": 5, "firstname": "john5", "lastname": "doe", "parentid": 3 } } } } }, "4": { "id": 4, "firstname": "john4", "lastname": "doe", "parentid": 0 } } 结果后,you will get

$user_data = App\User::where(["username"=>"admin", "password"=>bcrypt("test123")])->get();