R
R
Roman2017-12-03 01:38:09
PHP
Roman, 2017-12-03 01:38:09

How to mark checked the desired list item in a recursive function?

Wrote a recursive function to display a list, with a choice of radio input.
The question arose of how to mark a certain element, so that when the list is displayed, it would be marked by default.

function tree($arr, $par = '0',){

    foreach ($arr as $key => $value){

      if ($value['parent']==$par){
          if ($key == '1') {
            $checked = 'checked';
          }

          $tree.= '<li><input type="radio" name="cat" value="'.$key.'" '.$checked.'>'.$value['name'];
        }
      
        $tree.= tree($arr,$key);	

        $tree.='</li>';
      }
    }

    return '<ul>'.$tree.'</ul>';
  }

When the condition that the key is equal to 1 is met, adds a checked to all top-level elements. And it turns out that the last element is marked, and not the one that is needed.
How to be?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question