Sort multidimensional arrays by rows

I rack my brain trying to figure out how to do it right, I have this multidimensional array:

Array ( [0] => Array ( [time] => November 1st 10:10 [query] => movies [set] => 1 [matches] => No matching results [results] => 5 ) [1] => Array ( [time] => November 1st 10:10 [query] => cinemas [set] => 1 [matches] => No matching results [results] => 2 ) ) 

In real life there can be many more sub-arrays, but I say that I want to sort it by β€œquery” in alphabetical order, how can I achieve this?

I saw only solutions for an integer type or key index, the end result in this case would be:

 Array ( [0] => Array ( [time] => November 1st 10:10 [query] => cinemas [set] => 1 [matches] => No matching results [results] => 2 ) [1] => Array ( [time] => November 1st 10:10 [query] => movies [set] => 1 [matches] => No matching results [results] => 5 ) ) 

Thank you very much.

+7
source share
3 answers
 function querySort ($x, $y) { return strcasecmp($x['query'], $y['query']); } usort($myArray, 'querySort'); 
+15
source

I often use this function to sort multidimensional 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; } 

Creates a charm :)

+1
source

agreed with @Hammerite's answer, But here is the shortest way to do this sorting. You can achieve the same result starting with PHP 5.3 using an anonymous function :

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

17.1. - only syntax fix

+1
source

All Articles