Search code examples
phparraysnestedhtml-select

Nested option in select


I'm making a taxonomy system. I already created my recursive function and also a function to display my categories in a list (<ul>). Everything works fine with the list, every child element is move to the right...etc...

But now I need to do the same with a <select>. Here is what I've done so far :

private function _toHtml(&$list, $parent=-1, $pass = 0){
    $foundSome = false;
    for( $i=0,$c=count($list);$i<$c;$i++ ){
        $delay = '';
        if( $list[$i]['parent_id']==$parent ){
            if( $foundSome==false ){
                $delay .= str_repeat("--", $pass);
                $foundSome = true;
            }    
            echo '<option value="'. $list[$i]['id'] .'">'. $delay . $list[$i]['name'] .'</option>';
            $this->_toHtml($list,$list[$i]['id'],$pass+1);
        }
    }
}

The problem is, this works only on the first child elment, the others are kind of not considering at all. It looks basically like that :

Cinema
--English (sub cat for Cinema)
French (also a sub cat for Cinema)

When I expect to have :

Cinema
--English (sub cat for Cinema)
--French (also a sub cat for Cinema)

Any idea?

Thanks for your help


Solution

  • Whenever you face such problems, get more straight forward and forget about any premature optimization. Simplify your function by reducing nesting and proper naming of variables.

    private function _toHtml($list, $parent = -1, $level = 0)
    {
        foreach ($list as $entry) {
            if ($entry['parent_id'] != $parent) {
                continue;
            }
            printf('<option value="%s">%s%s</option>',
                $entry['id'],
                str_repeat('--', $level),
                $entry['name']
            );
            $this->_toHtml($list, $entry['id'], $level + 1);
        }
    }