问题
I have a two-dimensional array and want to sort it by name. I would like to use usort() with anonymous functions. How should my comparator function look like when I want to sort something alphabetically?
[names] => Array
(
[0] => Array
(
[name] => Baba
[prename] => Ali
)
[1] => Array
(
[name] => Pan
[prename] => Peter
)
)
To sort, I tried this:
usort($names, function cmp($a, $b) {
return strcmp($a['name'], $b['name']);
});
which gives me unexpected T_STRING, expecting '('
on the first line.
回答1:
You can use usort
$names = Array(
"0" => Array("name" => "B","prename" => "A"),
"1" => Array("name" => "D","prename" => "B"),
"2" => Array("name" => "A","prename" => "C"),
"3" => Array("name" => "B","prename" => "D")
);
Example 1
__xsort($names,"name");
var_dump($names);
Output
array
0 =>
array
'name' => string 'A' (length=1)
'prename' => string 'C' (length=1)
1 =>
array
'name' => string 'B' (length=1)
'prename' => string 'A' (length=1)
2 =>
array
'name' => string 'B' (length=1)
'prename' => string 'D' (length=1)
3 =>
array
'name' => string 'D' (length=1)
'prename' => string 'B' (length=1)
Example 2
__xsort($names,"prename");
var_dump($names);
Output
array
0 =>
array
'name' => string 'B' (length=1)
'prename' => string 'A' (length=1)
1 =>
array
'name' => string 'D' (length=1)
'prename' => string 'B' (length=1)
2 =>
array
'name' => string 'A' (length=1)
'prename' => string 'C' (length=1)
3 =>
array
'name' => string 'B' (length=1)
'prename' => string 'D' (length=1))
Function Used
function __xsort(&$names,$key) {
usort($names, function ($a, $b) use($key) {
if ($a[$key] == $b[$key]) {
return 0;
}
return ($a[$key] < $b[$key]) ? - 1 : 1;
});
return $names;
}
回答2:
The bug was not so obvious, but thinking again about the concept of anonymous functions, I got the hint. The function name can't be there. The correct solution for my exact problem is
usort($names, function ($a, $b) {
return strcmp($a['name'], $b['name']);
});
来源:https://stackoverflow.com/questions/12759575/comparator-functions-for-alphabetic-sorting-with-anonymous-functions