An awesome PHP 5.3 array multi-sort function

The following function is an adaptation of the code submitted by Thomas Heuer and posted here.

function multiSortArray($data, $field) {
        if (!is_array($field)) {    //if the field is given as a string, assume ascending
            $field = array($field=>true);

        usort($data, function($a, $b) use($field) {
            $retval = 0;
            foreach ($field as $fieldname=>$asc) {
                if ($retval == 0) {
                    $retval = strnatcmp($a[$fieldname], $b[$fieldname]);
                    if(!$asc) $retval *= -1;    //if
            return $retval;
        return $data;

The parameters are:

  • $data - an array of associative arrays. So for example, an array of Book records, where each Book record is simply an associative array with $key=>$value pairs such as array('title'=>'The Golder Compass', 'author'=>'Philip Pullman', 'published'=>'2000').
  • $field - this can be either a single string such as 'title', which will sort the $data array by the title field in ascending order. Alternatively, this can be an associative array($fieldname=>$asc), which sorts the data array by each field in sequence, in either ascending order (if $asc is true) or descending order otherwise.
The return value is simply the sorted array.

A typical usage example may be: self::multiSortArray($books, array('author'=>true,'published'=>false)). This would return an array of books sorted by author is ascending order, and by publish year in descending order where one author is part of multiple book records. 


  1. Very helpful multidimensional sort. Thanks!


Post a Comment

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word