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

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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误