2013-11-04 35 views
-1

你好,我發現PHP函數輸出數組中的html選擇列表。從php數組創建html選擇列表?

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' => 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 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>"); 

,但我需要重寫,以這樣的返回結果:

$select = "<select>"; 
$select .= printTree($list); 
$select .= "</select>"; 

echo $select; 
// or better 
return $select; 

問題是與遞歸,解決方案是填補陣列中的每個選項,但我不知道該怎麼做在遞歸函數中,還有

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

當foreach循環迭代時直接打印。

謝謝。

回答

0

所以我找出我的錯誤在哪裏,那只是因爲我用html選項標籤填充數組例如。

<option value="0">Start</option> 

但是用php函數print_r()我沒有看到任何數組值,當我檢查DOM元素時就沒有任何東西。

所以這裏是我的最終解決方案: 此功能填充值在多維陣列,進一步需要

# edited printTree() function, renamed to toSEL() 
# $array - data array like above, 
# $r - to correct iterate, $p - parent id, 
# $currentID - what id is selected 

function toSEL($array, $r = 0, $p = null, $currentID=null){ 
    foreach($array as $value){ 
     $dash = ($value[parent] == 0) ? '' : str_repeat('-', $r) .' '; 
     if($value[id]==$currentID){ 
      $html[] = '<option value="'.$value[id].'" selected="selected">'.$dash.$value[name].'</option>'; 
     }else{ 
      $html[] = '<option value="'.$value[id].'">'.$dash.$value[name].'</option>'; 
     } 

     if($value['parent'] == $p){ 
      // reset $r 
      $r = 0; 
     } 
     if(!empty($value[children])){ 
      $html[] = toSEL($value[children], ++$r, $value[parent], $currentID); 

     } 

    } 

    return $html; 
} 

從多維數組轉換成一名維

$aNonFlat = toSEL($list, 0, null, $currentID); 

$result = array(); 
array_walk_recursive($aNonFlat,function($v, $k) use (&$result){ $result[] = $v; }); 

那麼如果需要輸出HTML使用一些簡單的循環。

$html = '<select>'; 
foreach($result as $res){ 
    $html .= $res; 
} 
$html .='</select>'; 
echo $html;