0

I have got an array full with items like these:

array(
    array(
        'id' => 1,
        'name' => 'parent 1',
        'parent_id' => null
    ),
    array(
        'id' => 2,
        'name' => 'child of parent 1',
        'parent_id' => 1
    ),
    array(
        'id' => 3,
        'name' => 'grand child of parent 1',
        'parent_id' => 2
    ),
    array(
        'id' => 4,
        'name' => 'parent 2',
        'parent_id' => null
    ),
    array(
        'id' => 5,
        'name' => 'child of parent 2',
        'parent_id' => 4
    ),
);

And my question is: How can i build a tree for a known child? For example if i know the id is 3, i need to get an array of items including ids 1,2 and 3.

Thanks.

cnkt
  • 2,943
  • 5
  • 30
  • 43

1 Answers1

0

Maybe sth like this:

function build($tab, $id)
{
    $res = array();
    $node = $tab[$id];
    $i = 0;

    do
    {
        $res[$i] = node;
        $node = $tab[$node['parent_id']];
        $i++;
    } while( $node != null);

    return $res;

}
pejotr
  • 120
  • 6