JNL
JNL

Reputation: 13

PHP array sort / select option form

I have a form in PHP. It is unsorted. I would like to sort it. How would I go by it. This is the following PHP code I have. Thanks for help in advance.

<select id="school_name" name="school_name">
    <option value="">Select School</option>
    <?php for($c=0; $c<sizeof($school_details); $c++){?>                                    
    <option value="<?php echo stripslashes($school_details[$c]["title"]); ?>" 
    <?php if($school_details[$c]["title"]==$appInfo["school_name"]){?> selected="selected" <?php } ?> ><?php echo stripslashes($school_details[$c]["title"]); ?>
    </option>                                 
    <?php } ?>
</select>

Upvotes: 1

Views: 4039

Answers (3)

Hamid
Hamid

Reputation: 1563

try somthing like this:

$str = "<select id='school_name' name='school_name'>";
    $options = "";
    for($i = 0; $i<10;$i++)
    {
        $RandomNum = rand(0, 100);
        $options = "" . $options . ("<option value='$RandomNum'>&nbsp" . $RandomNum . "&nbsp </option>\n");
    }

    $optionsArray = explode("\n", $options);
    natsort($optionsArray);
    $sorted_option = implode("|",$optionsArray);

    $select = $str.$sorted_option."</select>";

    echo $select;

Upvotes: 2

halabuda
halabuda

Reputation: 384

You could implement a user defined sort to achieve this. Assuming you want to sort by the value of the 'title' element you would simply add this before your opening select tag:

<?php
uasort($school_details,'cmp');
function cmp($a,$b){
  if($a['title'] == $b['title']){return 0;}
  return ($a['title'] < $b['title']) ? -1 : 1; 
}
?>

Upvotes: 0

wogsland
wogsland

Reputation: 9508

PHP provides a number of methods for sorting: http://www.php.net/manual/en/array.sorting.php

Upvotes: 0

Related Questions