Skip to content
Advertisement

How to show parent and child items form array in php

I am new at php. Maybe a simple question.. I want to make parent->child view. I have an array like this: With key id and key parent.

How to draw in cycle correct structure? Maybe at first I need to create function for creating the tree ?

    -Apple
     -Services
    Duster


  array(3) {
      [0]=>
      array(6) {
        ["id"]=>
        string(3) "127"
        ["title"]=>
        string(5) "Apple"
        ["deleted"]=>
        string(1) "0"
        ["parent"]=>
        NULL
        ["usp_id"]=>
        string(3) "445"
        ["user_id"]=>
        NULL
      }
      [1]=>
      array(6) {
        ["id"]=>
        string(3) "159"
        ["title"]=>
        string(14) "Renault Duster"
        ["deleted"]=>
        string(1) "0"
        ["parent"]=>
         NULL
        ["usp_id"]=>
        string(3) "495"
        ["user_id"]=>
        NULL
      }
      [2]=>
      array(6) {
        ["id"]=>
        string(1) "7"
        ["title"]=>
        string(8) "Services"
        ["deleted"]=>
        string(1) "0"
        ["parent"]=>
          string(3) "127"
        ["usp_id"]=>
        string(2) "79"
        ["user_id"]=>
        string(3) "275"
      }
    }

Advertisement

Answer

Cycle through the source array $arr to detect records that have a parent (not null). When a child record is found, push it into the parent.

foreach ($arr as $key0 => $record) {
    if (null !== $record['parent']) {
        foreach ($arr as $key1 => $parent) {
            if ($parent['id'] === $record['parent']) {
                $arr[$key1]['children'][] = $record; // push child into parent
                unset($arr[$key0]); // delete child
            }
        }
    }
}

demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement