John Davidson

multidimensional array - PHP logic to build multi level tree

0 comments
Message:


Updated


I have the following array, for example:


[{id:1},{id:2}{id:3},{id:4},{id:5},...{id:20}]


May I ask how to generate a JSON object as below in order to achieve the following tree in Image 1? It does not need a parent id as it is first come first serve and each node will only have direct 3 childs.


I think it will run through a function and append the children to the object. Also I wish to control the number of childrens in the future too. Thanks in advance


JSON object


{
"tree": {
"id": 1,
"children": [
{
"id": 2,
"children": [
{
"id": 5,
"children": [
{
"id": 11
},
{
"id": 12
},
{
"id": 13
}
]
},
{
"id": 6
},
{
"id": 7
}
]
},
{
"id": 3,
"children": [
{
"id": 8
},
{
"id": 9
},
{
"id": 10
}
]
},
{
"id": 4,
"children": [
{
"id": 11
},
{
"id": 12
},
{
"id": 13
}
]
}
]
}
}

Image 1: the tree illustration




My Answer:
{
"id": 1,
"children": [
{
"id": 2,
"children": [
{
"id": 4
},
{
"id": 5
},
{
"id": 6
}
]
},
{
"id": 3,
"children": [
{
"id": 7
},
{
"id": 8
},
{
"id": 9
}
]
},
{
"id": 10,
"children": [
{
"id": 11
},
{
"id": 12
},
{
"id": 13
}
]
}
]
}

Rate this post

3 of 5 based on 9541 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us