I’m able to populate my dropdown list with the values in my database. However, the list is unsorted and hectic due to large values. How can I have this list sorted in alphabetical order when the user clicks on the dropdown? My code is below.
<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>
2
Answers
I’m not sure if I follow correctly, but I’ve set up an unsorted multi-dimensional array similar to yours:
and used a print_r() function and it gave me this:
Then to sort it, I used this method:
That’s a usort() and it sorts each array by first_name index.
Below is what the print_r() function returned:
As you can see, my $allEmployees array variable is sorted and from there you can use it on your
foreach
loop to create dropdown menu items.Note: This seems like something you should do on your database when you are querying your data, e.g:
SELECT * FROM EMPS ORDER BY first_name DESC
, but if you are looking for a strictly PHP sort, then the usort method using the arrow function should do the trick.