我正在创建一个由数据库填充的多个下拉列表,有时会预先选择一个值。它所从的表格中有一个或多个客户以逗号分隔。
示例:“John Doe”可能是一个条目,“Jane Smith,John Doe,Guy Inc。”和另一个像“Jane Smith,Tom琼斯,“可能是下一个。
要生成不同选项的列表,我使用以下代码:
<?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 :(得分: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>';
}
?>
通过这种方式,您首先获得客户然后加入标记,而不是试图以非常混乱的方式破坏/爆炸。希望这会有所帮助。