Sorting Associative Arrays Alphabetically


 ksort($a); asort($a); 


Sorting associative arrays can be done in one of several ways:

  • Sort by keys, leave key-value association intact: Use ksort().

  • Sort by keys in reverse order, leave key-value association intact: Use krsort().

  • Sort by values, leave key-value association intact: Use asort().

  • Sort by values in reverse order, leave key-value association intact: Use arsort().

Sorting an Associative Array (sort_a.php)
 <pre> <?php   $a = array('one' => 'I', 'two' => 'II', 'three' =>     'III', 'four' => 'IV');   ksort($a);   print_r($a);   asort($a);   print_r($a); ?> </pre> 

The preceding code shows these functions in action; Figure 2.3 shows the result.

Figure 2.3. Sorting associative arrays.


NOTE

Trying to use sort() or rsort() with associative arrays worksbut the keys are then all lost.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net