title: Create html select list from php array?
body: <p>Hello I find php function that outputs html select list from array.</p>
  
  <pre><code>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;
  }
  
  
  $rows = array(
      array ('id' =&gt; 1, 'name' =&gt; 'Test 1', 'parent' =&gt; 0),
      array ('id' =&gt; 2, 'name' =&gt; 'Test 1.1', 'parent' =&gt; 1),
      array ('id' =&gt; 3, 'name' =&gt; 'Test 1.2', 'parent' =&gt; 1),
      array ('id' =&gt; 4, 'name' =&gt; 'Test 1.2.1', 'parent' =&gt; 3),
      array ('id' =&gt; 5, 'name' =&gt; 'Test 1.2.2', 'parent' =&gt; 3),
      array ('id' =&gt; 6, 'name' =&gt; 'Test 1.2.2.1', 'parent' =&gt; 5),
      array ('id' =&gt; 7, 'name' =&gt; 'Test 2', 'parent' =&gt; 0),
      array ('id' =&gt; 8, 'name' =&gt; 'Test 2.1', 'parent' =&gt; 7),
  );
  
  $tree = buildTree($rows);
  // print_r($tree);
  
  function printTree($tree, $r = 0, $p = null) {
    foreach ($tree as $i =&gt; $t) {
      $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) .' ';
      printf("\t&lt;option value='%d'&gt;%s%s&lt;/option&gt;\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("&lt;select&gt;\n");
  printTree($tree);
  print("&lt;/select&gt;");
  </code></pre>
  
  <p>but I need to rewrite to return result like this:</p>
  
  <pre><code>$select = "&lt;select&gt;";
  $select .= printTree($list);
  $select .= "&lt;/select&gt;";
  
  echo $select;
  // or better
  return $select;
  </code></pre>
  
  <p>The problem is with recursion, solution is to fill each option in array, but I don't know how to do that in recursive functions, and also</p>
  
  <pre><code>printf("\t&lt;option value='%d'&gt;%s%s&lt;/option&gt;\n", $t['id'], $dash, $t['name']);
  </code></pre>
  
  <p>prints directly when foreach loop iterate. </p>
  
  <p>Thanks.</p>