multi dimensional array sorting by string multi dimensional array sorting by string php php

multi dimensional array sorting by string


function querySort ($x, $y) {    return strcasecmp($x['query'], $y['query']);}usort($myArray, 'querySort');


I often use this function to sort multi dimensional arrays:

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {         if(is_array($array) && count($array)>0) {             foreach(array_keys($array) as $key) {                 $temp[$key]=$array[$key][$index];             }             if(!$natsort) {                 if ($order=='asc') {                     asort($temp);                 } else {                         arsort($temp);                 }             }             else              {                 if ($case_sensitive===true) {                     natsort($temp);                 } else {                     natcasesort($temp);                 }                if($order!='asc') {                  $temp=array_reverse($temp,TRUE);                }             }             foreach(array_keys($temp) as $key) {                  if (is_numeric($key)) {                     $sorted[]=$array[$key];                 } else {                         $sorted[$key]=$array[$key];                 }             }             return $sorted;         }     return $sorted; }

Works a charm :)


agreed with @Hammerite answer,But here is a shortest way of doing this kind of sorting. You can achieve the same result starting from PHP 5.3, by using an anonymous function:

 usort($myArray, function($x, $y) {       return strcasecmp($x['query'] , $y['query']); });

17.1. - only syntax fix