我可以使用数据库中的值填充下拉列表。然而,由于值很大,该列表未排序且繁忙。当用户单击下拉列表时,如何使该列表按字母顺序排序?我的代码如下。
<div class="form-group">
<label class="control-label">Employee Name</label>
<select id="uni_name_drpdwn" class="form-control custom-select" name="emid" data-placeholder="Choose a Category" tabindex="1" value="" required>
<?php foreach($allemployees as $value): ?>
<option value="<?php echo $value->em_id ?>"><?php echo $value->first_name.' '.$value->last_name ?></option>
<?php endforeach; ?>
</select>
</div>
You can assign an id to the list and in a js file you can select it by id and add sort(). For example:
function ordenarListaDesplegable() {
var selectElement = document.getElementById("miListaDesplegable");
var options = selectElement.options;
var arr = [];
for (var i = 0; i < options.length; i++) {
arr.push(options[i].text);
}
arr.sort();
for (var j = 0; j < arr.length; j++) {
options[j].text = arr[j];
options[j].value = "valor" + (j + 1);
}
}
var miListaDesplegable = document.getElementById("miListaDesplegable");
miListaDesplegable.addEventListener("click", ordenarListaDesplegable);
我不确定我是否遵循正确,但我已经设置了一个与您类似的未排序的多维数组:
$allEmployees = [
1 => [
'id' => 1,
'first_name' => 'Jane',
'last_name' => 'Smith',
'salary' => 18000
],
2 => [
'id' => 2,
'first_name' => 'Micheal',
'last_name' => 'Scott',
'salary' => 21000
],
3 => [
'id' => 3,
'first_name' => 'Kelvin',
'last_name' => 'Malone',
'salary' => 16500
]
];
并使用了 print_r() 函数,它给了我这个:
Array(
[1] => Array
(
[id] => 1
[first_name] => Jane
[last_name] => Smith
[salary] => 18000
)
[2] => Array
(
[id] => 2
[first_name] => Micheal
[last_name] => Scott
[salary] => 21000
)
[3] => Array
(
[id] => 3
[first_name] => Kelvin
[last_name] => Malone
[salary] => 16500
)
)
然后为了排序,我用了这个方法:
usort($allEmployees, fn($a, $b) => $a['first_name'] <=> $b['first_name']);
这是一个 usort(),它按名字索引对每个数组进行排序。
以下是 print_r() 函数返回的内容:
Array (
[0] => Array
(
[id] => 1
[first_name] => Jane
[last_name] => Smith
[salary] => 18000
)
[1] => Array
(
[id] => 3
[first_name] => Kelvin
[last_name] => Malone
[salary] => 16500
)
[2] => Array
(
[id] => 2
[first_name] => Micheal
[last_name] => Scott
[salary] => 21000
)
)
如您所见,我的 $allEmployees 数组变量已排序,您可以在
foreach
循环中使用它来创建下拉菜单项。
注意:这似乎是您在查询数据时应该在数据库上执行的操作,例如:
SELECT * FROM EMPS ORDER BY first_name DESC
,但如果您正在寻找严格的 PHP 排序,那么使用箭头函数的 usort 方法应该可以解决问题。
您可以使用
select
子句直接在 SQL 查询中对下拉列表 ORDER BY
项目进行排序:
$allemployees = $db->query("SELECT * FROM employees ORDER BY first_name, last_name ASC")->fetchAll();
这将首先按
first_name
对您的员工进行排序,然后按 last_name
进行排序,两者均按 升序。
您的下拉菜单
select
的 HTML/PHP 代码不会改变:
<div class="form-group">
<label class="control-label">Employee Name</label>
<select id="uni_name_drpdwn" class="form-control custom-select" name="emid" data-placeholder="Choose a Category" tabindex="1" value="" required>
<?php foreach($allemployees as $value): ?>
<option value="<?php echo $value->em_id ?>"><?php echo $value->first_name.' '.$value->last_name ?></option>
<?php endforeach; ?>
</select>
</div>