Skip to content

Instantly share code, notes, and snippets.

@IrcDirk
Forked from mgsmus/nested_array.php
Created November 9, 2018 12:27
Show Gist options
  • Select an option

  • Save IrcDirk/938b26176aab813b8bc2a485832f68a0 to your computer and use it in GitHub Desktop.

Select an option

Save IrcDirk/938b26176aab813b8bc2a485832f68a0 to your computer and use it in GitHub Desktop.

Revisions

  1. @mgsmus mgsmus created this gist Mar 7, 2018.
    131 changes: 131 additions & 0 deletions nested_array.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,131 @@
    function makeNested($source) {
    $nested = array();

    foreach ( $source as &$s ) {
    if ( is_null($s['parent_id']) ) {
    // no parent_id so we put it in the root of the array
    $nested[] = &$s;
    }
    else {
    $pid = $s['parent_id'];
    if ( isset($source[$pid]) ) {
    // If the parent ID exists in the source array
    // we add it to the 'children' array of the parent after initializing it.

    if ( !isset($source[$pid]['children']) ) {
    $source[$pid]['children'] = array();
    }

    $source[$pid]['children'][] = &$s;
    }
    }
    }
    return $nested;
    }

    /*
    $source = array(
    1 => array(
    'name' => 'Parent One',
    'parent_id' => null
    ),
    2 => array(
    'name' => 'Parent Two',
    'parent_id' => null
    ),
    3 => array(
    'name' => 'Child One',
    'parent_id' => 1
    ),
    4 => array(
    'name' => 'Child Two',
    'parent_id' => 1
    ),
    5 => array(
    'name' => 'Child Three',
    'parent_id' => 2
    ),
    6 => array(
    'name' => 'Child Four',
    'parent_id' => 5
    ),
    7 => array(
    'name' => 'Child Five',
    'parent_id' => 2
    ),
    8 => array(
    'name' => 'Child Six',
    'parent_id' => 3
    ),
    9 => array(
    'name' => 'Child Seven',
    'parent_id' => 6
    )
    );

    Array
    (
    [0] => Array
    (
    [name] => Parent One
    [parent_id] =>
    [children] => Array
    (
    [0] => Array
    (
    [name] => Child One
    [parent_id] => 1
    [children] => Array
    (
    [0] => Array
    (
    [name] => Child Six
    [parent_id] => 3
    )
    )
    )

    [1] => Array
    (
    [name] => Child Two
    [parent_id] => 1
    )
    )
    )

    [1] => Array
    (
    [name] => Parent Two
    [parent_id] =>
    [children] => Array
    (
    [0] => Array
    (
    [name] => Child Three
    [parent_id] => 2
    [children] => Array
    (
    [0] => Array
    (
    [name] => Child Four
    [parent_id] => 5
    [children] => Array
    (
    [0] => Array
    (
    [name] => Child Seven
    [parent_id] => 6
    )
    )
    )
    )
    )
    [1] => Array
    (
    [name] => Child Five
    [parent_id] => 2
    )
    )
    )
    )
    */