I have a task where I must to get hierarchy tree from given array. An arrays inside array looks:
$commentsArray = [
[1, 1, 'Comment 1'],
[2, 1, 'Comment 2'],
[3, 2, 'Comment 3'],
[4, 1, 'Comment 4'],
[5, 2, 'Comment 5'],
[6, 3, 'Comment 6'],
[7, 7, 'Comment 7'],
];
now I need to get output into html like:
Comment 1
-- Comment 2
----Comment 3
------Comment 6
----Comment 5
--Comment 4
Comment 7
My code doesn’t work:
<?php
$commentsArray = array(
array(
'id' => 1,
'parent_id' => 1,
'content' => 'Comment 1'
),
array(
'id' => 2,
'parent_id' => 1,
'content' => 'Comment 2'
),
array(
'id' => 3,
'parent_id' => 2,
'content' => 'Comment 3'
),
...
);
$new = array();
foreach ($commentsArray as $comment){
$new[$comment['parent_id']][] = $comment;
}
$tree = createTree($new, array($commentsArray[0]));
echo '<pre>';
print_r($tree);
echo '</pre>';
function createTree(&$list, $parent){
$tree = array();
foreach ($parent as $k=>$l){
if(isset($list[$l['id']])){
$l['children'] = createTree($list, $list[$l['id']]);
}
$tree[] = $l;
}
return $tree;
}
I tried to run script without first element of $commentsArray and it works but I need the first element
3
Answers
I did it myself. But Thanks anyway!
Then in html page:
You could use two functions:
Output: