2014-04-23 83 views
0

我創建了一個數據庫填充的多個下拉列表,有時會有一個預先選定的值。它從中抽取的表格有一個或多個由逗號分隔的客戶。帶有數組的多個分隔符

例如:「李四」可能是一個條目,「簡·史密斯,約翰·多伊,蓋伊公司」和其他類似「簡·史密斯,湯姆·瓊斯,」可能是下一個。

要生成的不同選項的列表,我用這個代碼:

<?php 

$result2 = "SELECT DISTINCT Customer FROM CustomerTracker WHERE Customer NOT IN ('', '---< Select Customer >---', 'Left Blank')"; 
$rs2 = odbc_exec($conncmse,$result2); 
$CustomerData0 = ''; 

while($row = odbc_fetch_array($rs2)) { 
    $Customer0 = $row['Customer']; 
    foreach (explode(',', $Customer0) as $Customer) { 
     $CustomerData0 .= "<option>" . trim($Customer, " ") . "</option>"; 
    } 
} 

$CustomerData = implode('</option><option>',array_unique(explode('</option><option>', $CustomerData0))); 

echo $CustomerData; 

echo '<select name="Select1" multiple="multiple">'; 
echo $CustomerData; 
echo '</select>'; 

它工作正常,但如果我想有一個預先選定的客戶,我想出了這個:

$SelectedCustomer = "John Doe"; 

$result2 = "SELECT DISTINCT Customer FROM CustomerTracker WHERE Customer NOT IN ('', '---< Select Customer >---', 'Left Blank')"; 
$rs2 = odbc_exec($conncmse,$result2); 
$CustomerData0 = ''; 
while($row = odbc_fetch_array($rs2)) { 
    $Customer0 = $row['Customer']; 
    foreach (explode(',', $Customer0) as $Customer) { 
     if(strpos($SelectedCustomer, $Customer) !== false) { 
      $CustomerData0 .= "<option selected='selected'>" . trim($Customer, " ") . "</option>";$SelectedCustomer = ""; 
     } 
     else { 
      $CustomerData0 .= "<option>" . trim($Customer, " ") . "</option>"; 
     } 
    } 
} 

$CustomerData = implode("</option><option>",array_unique(explode("</option><option>", $CustomerData0))); 

?> 

我遇到的問題是我只能使用分隔符</option><option>,所以我得到了所選客戶的副本。我真正需要的是有多個分隔符的方法。有任何想法嗎?

回答

0

剛開始我對這個問題的理解有點困難,但仔細一看,看到了自己在做什麼。我認爲你過於複雜了。

$selectedCustomer = "John Doe"; 
$customers = array(); 
while($row = odbc_fetch_array($rs2)) { 
    //get rid of trailing comma 
    $customersString = rtrim($row['Customer'],','); 
    //first populate an array with all the customers. 
    foreach(explode(',', $customersString) as $customer) 
     $customers[] = $customer; 
} 
//now eliminate duplicates 
$customers= array_unique($customers); 
//now create the string with options 
foreach($customers as $customer) 
{ 
    $selected = trim($customer) == $selectedCustomer ? 'selected="selected" ': ''; 
    $CustomerData = '<option '.$selected.'>'.$customer.'</option>'; 
} 

?> 

這樣你第一次獲得客戶,然後投入的標記,而不是試圖破滅/在一個非常混亂的方式就可以了爆炸。希望這可以幫助。

+0

我試圖讓我的腦袋也圍繞它 - 認爲你釘了它。 – cstrat

+0

@strat,是的,我花了一段時間才弄清楚他的最終目標是什麼。當試圖將它與標記混合時,有時爆炸/爆炸更容易混淆而不是有用。 – Bryan