douding7189 2015-02-25 14:22
浏览 247
已采纳

PHP:如何使用匿名函数usort?

I've an array of array.

I'm trying this code to sort main array based of a field of every single element of the main array.

$field = $this->sorting;
usort($this->out_table["rows"], function($a, $b) use ($field) {
        return strnatcmp($a[$field], $b[$field]);
});

But I got this

 Parse error: syntax error, unexpected T_FUNCTION 

Referred to the second line, the one which starts with 'usort'

What am I missing?

My php version is

PHP 5.2.4-2ubuntu5.27 with Suhosin-Patch 0.9.6.2 (cli) (built: Mar 11 2013 14:14:48)
  • 写回答

3条回答 默认 最新

  • doucan2102 2015-02-25 14:29
    关注

    PHP 5.2 doesn't support anonymous functions. Anonymous functions are instances of the Closure class, which as the docs say, wasn't introduced until 5.3... PS: _upgrade your PHP version, 5.2 was EOL'ed ages ago.

    For now, though, you're best off writing your own class, pass the $field value to that class' instance and use the array-style callable argument:

    class Sorter
    {
        protected $field = null;
        public function __construct($field)
        {
            $this->field = $field;
        }
        public function sortCallback($a, $b)
        {
            return strnatcmp($a[$this->field], $b[$this->field]);
        }
    }
    $sorter = new Sorter($field);
    usort($this->out_table["rows"], array($sorter, 'sortCallback'));
    

    Which is basically what a Closure instance does, the anonymous function business is syntactic sugar in this case. The advantage of a class like this is that you could add some more sort-callbacks to it, and keep it handy as a sort of utility class with a sortAscending and sortDescending callback method, for example. Along with options you can set on the instance that make the sorter use strict (type and value) comparison where it's needed....

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化