2014-02-28 56 views
1

我有一個while循環提取agentspec表中的所有值,並將它們設置爲選擇字段中的選項。選擇具有嵌入在while循環中的Optgroup的組

我在agentspec表中的值由category字段分組,我想使用category字段作爲我的optgroup標籤。

這是我試過的。它當前輸出所有category字段值,然後輸出所有spec值 例如。

Category: Farmer 
Category: Farmer 
Category: Farmer 
Category: Colour 
Category: Colour 
Spec: Grain 
Spec: Sand 
Spec: Fruit 
Spec: Red 
Spec: Blue 

我按照什麼羣體,它們在category場設置要輸出的spec值。

例如。

Category: Farmer 
Spec: Grain 
Spec: Sand 
Spec: Fruit 
Category: Colour 
Spec: Red 
Spec: Blue 

代碼:

$st = DBase::singleton() 
      ->prepare(
       'select * ' . 
       'from `agentspec` ' . 
       'limit 0,30'); 

    $option = ''; 
    $optgroup = ''; 
    if ($st->execute()) 
    { 
      while ($row = $st->fetch(PDO::FETCH_OBJ)) 
      { 
    $id = $row->id; 
    $cat = $row->category; 
    $spec = htmlspecialchars($row->spec); 
    $desc = htmlspecialchars($row->desc); 

    $optgroup .= '<optgroup label= '.$cat.'></optgroup>'; 
    $option .= '<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>'; 

    } 
    } 


    ?> 


    <select id="selectbox" name="" class=form-control> 
    <option selected="selected">Select a Specialist Area 
    </option> 
    <?php echo $optgroup;?> 
    <?php echo $option;?> 

</select> 
+0

這是一個簡單的_control break_你想編程h因此,請閱讀。 – CBroe

回答

1

一個選項是OPTGROUP的子元素,所以你必須做這樣的事情 該粗fiddle example:你片斷

改寫版本:

<?php 
     $st = DBase::singleton() 
        ->prepare(
         'select * ' . 
         'from `agentspec` ' . 
         'limit 0,30'); 


     $optHtml= ''; 
     $optgroups = array(); 

     if ($st->execute()) 
     { 
      while ($row = $st->fetch(PDO::FETCH_OBJ)) 
      { 
       $id = $row->id; 
       $cat = $row->category; 
       $spec = htmlspecialchars($row->spec); 
       $desc = htmlspecialchars($row->desc); 
       if (!array_key_exists($cat, $optgroups)) { 
        $optgroups[$cat] = ""; 
       } 
       $optgroups[$cat].='<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>'; 
      } 
      foreach($optgroups as $label=>$optionsHtml) { 
       $optHtml.= '<optgroup label="'.$label.'">'.$optionsHtml.'</optgroup>'; 
      } 
     } 


?> 

<select id="selectbox" name="" class=form-control> 
    <option selected="selected">Select a Specialist Area</option> 
    <?php echo $optHtml; ?> 
</select> 
+0

工程真棒!非常感謝 – Stephenmelb