0

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.

4

2 回答 2

1

这个 bug 不是很明显,但再次思考匿名函数的概念,我得到了提示。函数名不能在那里。我的确切问题的正确解决方案是

usort($names, function ($a, $b) {
    return strcmp($a['name'], $b['name']);
});
于 2012-10-06T12:19:50.113 回答
1

您可以使用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")

        );

示例 1

__xsort($names,"name");
var_dump($names);

输出

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)

示例 2

__xsort($names,"prename");
var_dump($names);

输出

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 __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;
}
于 2012-10-06T12:10:22.537 回答