Tuesday, March 14, 2017

PHP format tree comments, categories, nested sets

Simple function for formatting tree. One cons - you need to pass all items (all comments of the post) to format them.

<?php

function formatTree($tree, $parent)
{
    $tree2 = array();
    foreach ($tree as $item) {
        if ($item['parent_id'] == $parent) {
            $tree2[$item['id']] = $item;
            $tree2[$item['id']]['child'] = formatTree($tree, $item['id']);
        }
    }

    return $tree2;
}


//for demo
$beforeTree = [
    ['id' => 1, 'parent_id' => 0],
    ['id' => 2, 'parent_id' => 1],
    ['id' => 3, 'parent_id' => 2],
    ['id' => 4, 'parent_id' => 0],
    ['id' => 5, 'parent_id' => 4],
    ['id' => 6, 'parent_id' => 4],
];
$afterTree = formatTree($beforeTree, 0);

var_dump($afterTree);

No comments:

Post a Comment