Nested List From Php Array For Dropdown Select Field

Nested list from PHP array for dropdown select field

function for bulid tree,




function buildTree(Array $data, $parent = 0) {

    $tree = array();

    foreach ($data as $d) {

        if ($d['parent'] == $parent) {

            $children = buildTree($data, $d['id']);

            // set a trivial key

            if (!empty($children)) {

                $d['_children'] = $children;

            }

            $tree[] = $d;

        }

    }

    return $tree;

}



static array values,

$rows = array(

array ('id' => 1, 'name' => 'Test 1', 'parent' => 0),


array ('id' => 2, 'name' => 'Test 1.1', 'parent' => 1),


array ('id' => 3, 'name' => 'Test 1.2', 'parent' => 1),


array ('id' => 4, 'name' => 'Test 1.2.1', 'parent' => 3),


array ('id' => 5, 'name' => 'Test 1.2.2', 'parent' => 3),


array ('id' => 6, 'name' => 'Test 1.2.2.1', 'parent' => 5),


array ('id' => 7, 'name' => 'Test 2', 'parent' => 0),


array ('id' => 8, 'name' => 'Test 2.1', 'parent' => 7),

);

$tree = buildTree($rows);

// print_r($tree);

function for printing tree,




function printTree($tree, $r = 0, $p = null) {

    foreach ($tree as $i => $t) {

        $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) .' ';

        printf("\t<option value='%d'>%s%s</option>\n", $t['id'], $dash, $t['name']);

        if ($t['parent'] == $p) {

            // reset $r

            $r = 0;

        }

        if (isset($t['_children'])) {

            printTree($t['_children'], ++$r, $t['parent']);

        }

    }

}



print("<select>\n");

printTree($tree);

print("</select>");

or if you use manual query just following this

$sql = Yii::app()->db->createCommand("select * from tbl_course_master ");

$client_group = $sql->queryAll();

$rows = array();

$rows = $client_group;

$tree = buildTree($rows);

print("<select class=‘txtbox’>\n");

printTree($tree);

print("</select>");

OUTPUT : :rolleyes:

<select>

&lt;option value='1'&gt;Test 1&lt;/option&gt;


&lt;option value='2'&gt;- Test 1.1&lt;/option&gt;


&lt;option value='3'&gt;- Test 1.2&lt;/option&gt;


&lt;option value='4'&gt;-- Test 1.2.1&lt;/option&gt;


&lt;option value='5'&gt;-- Test 1.2.2&lt;/option&gt;


&lt;option value='6'&gt;--- Test 1.2.2.1&lt;/option&gt;


&lt;option value='7'&gt;Test 2&lt;/option&gt;


&lt;option value='8'&gt;- Test 2.1&lt;/option&gt;

</select>

instead of




printTree($t['_children'], ++$r, $t['parent']);



there should be




printTree($t['_children'], $r + 1, $t['parent']);



or you will end up with every item under same parent having its own children to be rendered deeper in tree

i hav applied your thoughts it was just fantastic,

continue ur good job.