2013-08-25 135 views
0

我有function打印類別在dropdown菜單。如何下拉選擇使用PHP/MYSQL

function Cat_Parent(){ 
    $result = mysql_query("SELECT id, name, parent FROM cats ORDER BY name"); 
    $items = array(); 
    while($row = mysql_fetch_array($result)) 
     { $items[] = array('id' => $row['id'], 'label' => $row['name'], 'parent' => $row['parent']); 
    } 


// Loop using references to build a tree 
$childs = array(); 
foreach($items as &$item) 
{ 
    $childs[$item['parent']][] = &$item; 
} 

unset($item); 

foreach($items as &$item) 
{ 
    if(isset($childs[$item['id']])) 
    { 
     $item['children'] = $childs[$item['id']]; 
    } 
} 
// We now have a tree with 'children' key set on each node that has children 
$tree = $childs[0]; 

// Prepare a template and recursive closure (note reference on &$print) 
$tpl = '<option name="parent[]" value="%s">%s %s</option>'; 
$print = function($item, $indent = '') use (&$print, $tpl) 
{ 
    echo sprintf($tpl, $item['id'], $indent, $item['label']) . "\n"; 

    if(isset($item['children'])) 
    { 
     foreach($item['children'] as $child) 
     { 
      $print($child, $indent . '|--'); 
     } 
    } 
}; 

echo '<select name="parent"><option name="parent[]" value="0">------</option>'; 
// Call the function for each top-level node 
foreach($tree as $row) 
{ 
    $print($row); 
} 
echo '</select>'; 
    } 

這個工作,但我需要選擇value/id$_GET['id'] = value這樣的:

<select> 
<option value="1">cat1</option> 
<option selected value="2">cat2</option> <-- THIS Print Selected 
<option value="3">subcat2</option> 
<option value="4">cat3</option> 
<option value="5">cat4</option> 
</select> 

例如$_GET['id'] = 2,與value 2.所以選擇的選項如何選擇呢?

回答

1

在你的腳本試試這個代碼。如果GET的值與選項值相同,則定義一個具有「selected」值的變量。

注意$ sel變量。

// Prepare a template and recursive closure (note reference on &$print) 
$tpl = '<option name="parent[]"%s value="%s">%s %s</option>'; 
$print = function($item, $indent = '') use (&$print, $tpl) 
{ 
    $sel = (isset($_GET['id']) && $_GET['id'] == $item['id']) ? 'selected' : ' '; 
    echo sprintf($tpl, $sel, $item['id'], $indent, $item['label']) . "\n"; 

    if(isset($item['children'])) 
    { 
     foreach($item['children'] as $child) 
     { 
      $print($child, $indent . '|--'); 
     } 
    } 
}; 
0

你會想你的價值觀在模板中像這樣比較:

$tpl = '<option name="parent[]" %s value="%s">%s %s</option>'; 
$print = function($item, $indent = '') use (&$print, $tpl) 
{ 
    echo sprintf($tpl, $item['id'] == 2 ? 'selected="selected"' : '', $item['id'], $indent, $item['label']) . "\n"; 

    if(isset($item['children'])) 
    { 
     foreach($item['children'] as $child) 
     { 
      $print($child, $indent . '|--'); 
     } 
    } 
}; 
相關問題