PHP – multi-sort of associative array in PHP

January 6th, 2013 by Laeeq | No comments

This is a complete multi-sort example of associative array in PHP. We have first sorted an associative array by values in descending order then sorted an associative array by keys in ascending order.

  1. <?php
  2. $asso_arr = Array
  3. (
  4. ‘banana’ => 2,
  5. ‘cherry’ => 1,
  6. ‘orange’ => 3,
  7. ‘grapefruit’ => 1,
  8. ‘apple’ => 1
  9. );
  10. $values = array_values($asso_arr);
  11. $keys = array_keys($asso_arr);
  12. //first sort by values desc, then sort by keys asc
  13. array_multisort($values, SORT_DESC, $keys, SORT_ASC, $asso_arr);
  14. print_r($asso_arr);
  15. ?>

 

Output:

Array
(
[orange] => 3
[banana] => 2
[apple] => 1
[cherry] => 1
[grapefruit] => 1
)

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. No comments yet.
    1. No trackbacks yet.