0

I have some data on a MySQL database representing a tree structure, and I want to convert it into JSON. I have used a recursive function to read all the data but I have no idea on how to convert into an array.

Here is the recursive function:

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);
    }

}

And the following is the JSON result I'd like to have in the end:

[  
    {  
        "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

1 Answer 1

2
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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

now i can be able to display the data on json format with your suggested code. thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.