简体   繁体   中英

PHP/MYSQL -Need help sorting array alphabetically

I need the below codes to list venue names alphabetically in ascending order (AZ). Right now it's sorting the venues by when they were listed in the database. Where do I tweak?

     <?php for($ii = 1; $ii <= 10; $ii++): ?>
    <div class="bor_t menu_option_container"<?php if($ii != 1): ?> style="display: none;"<?php endif; ?>>
    <div class="mb20">
    <label class="ros_head alt_label" for="venue_option<?php echo $ii; ?>_note_field">VENUE OPTION <?php echo $ii; ?></label>
       <?php
            $venue_room_options = array();
            $venue_room_options["null"] = "Select a venue";

                            foreach($rooms as $room) {
                                $venue_room_options[$room->VenueID . '_' . 
                                $room->RoomID] = $room->VenueName . " - " . $room->RoomName;

                            }

                            echo form_dropdown('venue_selection' . $ii, $venue_room_options, ( set_value('venue_selection' . $ii) ) ? set_value('venue_selection' . $ii) : '1', 'id=""', array("id"=>"venue_option" . $ii));
                        ?>
                    </div> <!-- /.mb20 -->`

You can sort the array by using php array function asort().

add sort function here

<?php 
// your code 

 asort($venue_room_options);  // new line added
 echo form_dropdown('venue_selection' . $ii, $venue_room_options, ( set_value('venue_selection' . $ii) ) ? set_value('venue_selection' . $ii) : '1', 'id=""', array("id"=>"venue_option" . $ii));

 ....
?>

This will sort by venueName-roomName alphabetically

Right above your foreach loop, insert the following code:

sort($rooms);

For more information, please refer to: http://php.net/manual/en/function.sort.php

If you want to maintain keys association, use the function asort like

<?php
...
asort($venue_room_options);
echo form_dropdown('venue_selection' . $ii, $venue_room_options, ( set_value('venue_selection' . $ii) ) ? set_value('venue_selection' . $ii) : '1', 'id=""', array("id"=>"venue_option" . $ii));
...
?>

There are a lot of PHP functions to work with array sorting: http://php.net/manual/en/array.sorting.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM