我绞尽脑汁想弄清楚怎么做才对,我有这个多维数组
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
)
)
在现实生活中,可能有更多的子数组,但假设我想按"query"的字母顺序排序,我该如何实现这一点?
我只看到整数类型或键索引的解决方案,在这种情况下,最终结果将是:
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
)
)
function querySort ($x, $y) {
return strcasecmp($x['query'], $y['query']);
}
usort($myArray, 'querySort');
我经常使用这个函数对多维数组进行排序:
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:)
同意@Hammerite的答案,但这里有一种最短的排序方法。从PHP 5.3开始,您可以通过使用匿名函数:
来实现相同的结果。 usort($myArray, function($x, $y) {
return strcasecmp($x['query'] , $y['query']);
});
17.1。-唯一的语法修复