Jump to content

[SOLVED] Create Hierarchical Drop-Down List from Array


fraction

Recommended Posts

I'm trying to create a hierarchical drop-down list from an array i've created.  Totally stumped.

 

Here's a piece of the sample array:

 

 

 [0] => Array
        (
            [id] => 19
            [name] => Food
            [parentid] => 1
            [type] => 1
        )

    [1] => Array
        (
            [id] => 32
            [name] => Apple
            [parentid] => 19
            [type] => 1
        )

    [2] => Array
        (
            [id] => 33
            [name] => Orange
            [parentid] => 19
            [type] => 2
        )

 

 

I'd like to get to this point:

 

   

 <option value="19">Food</option>
      <option value="32"> - Apple</option>
       <option value="33"> - Orange</option>

 

 

Basically, creating a list like:

Parent1

-Child1

-Child2

--Subchild1

Parent2

 

etc.

 

Any help would be greatly appreciated.

Cheers.

Jon

 

 

Yes you need a recursive function

 

<?php
function printOptions ($options, $parent, $level=0)
{
    foreach ($options as $opt)
    {
       if ($parent == $opt['parentid'])
       {
           $indent = str_repeat('---', $level); 
           echo "<option value='{$opt['id']}'>$indent {$opt['name']}</option>\n";
           printOptions($options, $opt['id'], $level+1);
       }
             
    }
}

$options = array (
    Array
        (
            'id' => 19,
            'name' => 'Food',
            'parentid' => 1,
            'type' => 1
        ),

    Array
        (
            'id' => 32,
            'name' => 'Apple',
            'parentid' => 19,
            'type' => 1
        ),

    Array
        (
            'id' => 33,
            'name' => 'Orange',
            'parentid' => 19,
            'type' => 2
        )
);

echo "<select name='myselect'>\n" ;
// call function
printOptions ($options,1);
echo "</select>\n";
?>

Ok, I see what you're getting at. 

 

Trick here is, you're setting the parent in the function call.  I need to make that dynamic.  So we create everything for parent 1, then move on to the next parent in the array.

 

Example

Parent 1

- child 1

- child 2

-- sub-child 1

-- sub-child 2

Parent 2

- child 1

etc.

 

In another recursive function I built, i continued to call the same function until we reached a leaf on the tree, then moved on to the next parent.  Any chance that could work here?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.