使用匿名函数进行字母排序的比较器函数 [英] Comparator functions for alphabetic sorting with anonymous functions

查看:18
本文介绍了使用匿名函数进行字母排序的比较器函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,想按名称对其进行排序.我想将 usort() 与匿名函数一起使用.当我想按字母顺序排序时,我的比较器函数应该是什么样的?

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']);
});

这给了我 意外的 T_STRING,在第一行期待 ​​'('.

推荐答案

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

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']);
});

这篇关于使用匿名函数进行字母排序的比较器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆