Skip to content

Instantly share code, notes, and snippets.

@Vijaysinh
Created October 21, 2021 09:23
Show Gist options
  • Select an option

  • Save Vijaysinh/575704d4de5dd3619acde109926e724b to your computer and use it in GitHub Desktop.

Select an option

Save Vijaysinh/575704d4de5dd3619acde109926e724b to your computer and use it in GitHub Desktop.

Revisions

  1. Vijaysinh created this gist Oct 21, 2021.
    44 changes: 44 additions & 0 deletions RecursiveParentChild.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    <?php

    $arr = '[{"id":8,"parent":4,"name":"Food & Lifestyle"},{"id":2,"parent":1,"name":"Mobile Phones"},{"id":1,"parent":0,"name":"Electronics"},{"id":3,"parent":1,"name":"Laptops"},{"id":5,"parent":4,"name":"Fiction"},{"id":4,"parent":0,"name":"Books"},{"id":6,"parent":4,"name":"Non-fiction"},{"id":7,"parent":1,"name":"Storage"}]';

    $t = buildTree($arr);

    print_r($t);

    function buildTree(array $flatList)
    {
    $grouped = [];
    foreach ($flatList as $node){
    $grouped[$node['parent']][] = $node;
    }

    $fnBuilder = function($siblings) use (&$fnBuilder, $grouped) {
    foreach ($siblings as $k => $sibling) {
    $id = $sibling['id'];
    if(isset($grouped[$id])) {
    $sibling['children'] = $fnBuilder($grouped[$id]);
    }
    $siblings[$k] = $sibling;
    }
    return $siblings;
    };

    return $fnBuilder($grouped[0]);
    }

    function build_tree(&$items, $parentId = null) {
    $treeItems = [];
    foreach ($items as $idx => $item) {
    if((empty($parentId) && empty($item['parent'])) || (!empty($item['parent']) && !empty($parentId) && $item['parent'] == $parentId)) {
    $items[$idx]['children'] = build_tree($items, $items[$idx]['id']);
    $treeItems []= $items[$idx];
    }
    }

    return $treeItems;
    }



    ?>