我有这个数组数组,
Array
(
[0] => Array
(
[id] => 1
[title] => AP-2 (1)
)
[1] => Array
(
[id] => 2
[title] => AC-1 (2)
)
[2] => Array
(
[id] => 3
[title] => AB-3 (1)
)
[3] => Array
(
[id] => 4
[title] => AD-2 (3)
)
[4] => Array
(
[id] => 5
[title] => AE-2 (1)
)
),
我需要以一种看起来像这样的方式对其进行排序,
Array
(
[0] => Array
(
[id] => 1
[title] => AB-3 (1)
)
[1] => Array
(
[id] => 2
[title] => AC-1 (2)
)
[2] => Array
(
[id] => 3
[title] => AD-2 (3)
)
[3] => Array
(
[id] => 4
[title] => AE-2 (1)
)
[4] => Array
(
[id] => 5
[title] => AP-2 (1)
)
)
这里发生的事情基本上是按字母顺序使用title
键对数组进行排序,或者使用natsort()
或natcasesort()
对数组进行排序。我怎样才能真正进行排序?提前谢谢。
答案 0 :(得分:2)
function sorter($key){
return function ($a, $b) use ($key) {
return strcmp($a[$key], $b[$key]);
};
}
usort($arr, sorter('title'));
var_dump($arr);
对于5.3之前的PHP版本,请使用:
function sorter($arr, $index) {
foreach($arr as $key => $value) {
$arr2[$key] = strtolower($value[$index]);
}
asort($arr2);
foreach($arr2 as $key =>$value) {
$arr3[] = $arr[$key];
}
return $arr3;
}
var_dump(sorter($arr, 'title'));