Create Category tree with PHP, WordPress

How to create a category tree with PHP from Array. Many times we required creating a parent and child category tree. So let’s make it easy. just used below function for creating category tree.

<?php
function buildTree($items) {
    $childs = array();
    foreach($items as &$item) $childs[$item['parent_id']][] = &$item;
    unset($item);
    foreach($items as &$item) if (isset($childs[$item['id']]))
            $item['childs'] = $childs[$item['id']];
    return $childs[0];
}

Passed your category array to `buildTree` function like below.

Assume the category array look like below

$items = array(
    array(‘id’ => 55, ‘name’ => ‘Child Category’, ‘parent_id’ => 2),
    array(‘id’ => 54, ‘name’ => ‘Child Category’, ‘parent_id’ => 2),
    array(‘id’ => 2, ‘name’ =>parent Category’, ‘parent_id’ => 0),
    array(‘id’ => 42, ‘name’ => ‘Child Category’, ‘parent_id’ => 1),
    array(‘id’ => 43, ‘name’ => ‘Child Category’, ‘parent_id’ => 1),
    array(‘id’ => 1, ‘name’ =>parent Category’, ‘parent_id’ => 0),
);

Now I passed this array to `buildTree` function for creating the category tree.

$output = buildTree($items);
print_r($output);

The output is below

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => parent Category
            [parent_id] => 0
            [childs] => Array
                (
                    [0] => Array
                        (
                            [id] => 55
                            [name] => Child Category
                            [parent_id] => 2
                        )

                    [1] => Array
                        (
                            [id] => 54
                            [name] => Child Category
                            [parent_id] => 2
                        )

                )

        )

    [1] => Array
        (
            [id] => 1
            [name] => parent Category
            [parent_id] => 0
            [childs] => Array
                (
                    [0] => Array
                        (
                            [id] => 42
                            [name] => Child Category
                            [parent_id] => 1
                        )

                    [1] => Array
                        (
                            [id] => 43
                            [name] => Child Category
                            [parent_id] => 1
                        )

                )

        )

)

The output gets something like this just used a single function for creating category tree.

If you face any issue after using this code please write a comment.