jeudi 22 juin 2017

PHP Returning JSON with modified data

I want my categories list be nice formatted while return to user. What I get from database is:

[
{
    "id": 1,
    "name": "pet",
    "parent_id": null
},
{
    "id": 2,
    "name": "page",
    "parent_id": null
},
{
    "id": 3,
    "name": "dog",
    "parent_id": 1
},
{
    "id": 4,
    "name": "cat",
    "parent_id": 1
},
{
    "id": 5,
    "name": "rodent",
    "parent_id": 1
},...

I want it to keep tree structure, like:

{
    "id": 1,
    "name": "pet",
    "parent_id": null,
    "children": [
        {
            "id": 3,
            "name": "dog",
            "parent_id": 1
        },
        {
            "id": 4,
            "name": "cat",
            "parent_id": 1
        },...

etc.

Is there an easy way way to do it or I have to loop through the database results and create new organized array to return? What is the best approach to do that? The problem is that the subcategories could also have subcategories. Or maybe i should just keep structure I get from the database and add children id's as an array (as I can refer to them anyway)?

I would be grateful for your help.

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2sGp970
via IFTTT

Aucun commentaire:

Enregistrer un commentaire