stackoverflow community. Guys?) My goal is generate new array with [childs] item by checking, if item has parent_id and it's not null, i need to add into this parent_id childs. It works correctly, but if item inside of parent_id has another item as a child. It didn't work. Here's my function
public function makeNested($source) {
$nested = array();
foreach($source AS $key => $s)
{
$s['childs'] = [];
if (is_null($s['parent_id']))
{
$nested[$s['comment_id']] = $s;
}
else {
$pid = $s['parent_id'];
$nested[$pid]['childs'][] = $s;
}
}
return array_values($nested);
}
Here's my output.
{
"data": [
{
"comment_id": 1,
"page_id": 3,
"parent_id": null,
"user_id": 3,
"comment": "Hi, i am using new version of WhatsApp.",
"type_id": 4,
"first_name": "Custom name",
"last_name": "Custom name",
"photo": "images/257139.jpg",
"childs": [
{
"comment_id": 2,
"page_id": 3,
"parent_id": 1,
"user_id": 2,
"comment": "I'm a child of comment_id 1",
"type_id": 4,
"first_name": "Custom name",
"last_name": "Custom name",
"photo": null,
"childs": []
}
]
},
{
"childs": [
{
"comment_id": 33,
"page_id": 3,
"parent_id": 2,
"user_id": 1,
"comment": "I'm a child of a child. 1 comment my grandfather xD",
"type_id": 4,
"first_name": "Custom name",
"last_name": "Custom name",
"photo": null,
"childs": []
}
]
}
]
}