Sorting PHP associative arrays

29 Sep 2011 | Posted by: Paul Whittington

There are times when you cannot sort the the order of a data set as you retrieve it from the database, and you need to sort it in script. The function below I wrote a long time ago but use all of the time.

Simply pass in the array, the array key you want to sort on, e.g. 

$customerArray = sortArrayByKey ($customerArray, "surname");

 

function sortArrayByKey ($key, $array, $desc=false){
    $sortArray = array();
    $returnArray = array();
    foreach ($array as $index=>$value) {
        $sortArray[$index] = $value[$key];
    }
    asort ($sortArray);
    foreach ($sortArray as $index=>$value) {
        $returnArray[] = $array[$index];
    }
    if ($desc) {
        return $returnArray = array_reverse($returnArray);
    } else {
        return ($returnArray);
    }
}

 

Please rate this article

Click the stars below to give this article a mark out of 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 5 / 10


Post your comments...

We would really appreciate any comments or additions that you have. Include a link in your comment and if we think your comment is appropriate we will publish it. If found this article in any way useful we would really appreciate you bookmarking the page with any of the social bookmarking links provided.



Name:
(optional, shown on site)
Email:
(optional, never shown on site)
Code:
(case sensitive)
captcha
Your feedback: