Comparator functions for alphabetic sorting with anonymous functions [closed]

£可爱£侵袭症+ 提交于 2019-12-13 06:06:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!