【问题标题】:Better PHP usort()更好的 PHP usort()
【发布时间】:2016-11-22 13:19:40
【问题描述】:

我需要合并并排序两个具有不同数据结构的数组(无法在 MySQL 查询中排序),但两者都有一个 created_on 字段。

所以我将usort() 与自定义函数一起使用。

在我的控制器中

usort(merged_array, 'sort_records');

在我的辅助函数中

if(!function_exists('sort_records')){
  function sort_records($a,$b){
    if ( $a['created_at'] == $b['created_at'] )
      return 0;
    if ( $a['created_at'] < $b['created_at'] )
       return -1;
    return 1;
  } 
}

我想让这个sort_records() 函数可重用。所以我可以将它与其他数组一起使用。也许像..

function sort_records($a,$b,$index){
  if ( $a[$index] == $b[$index] )
     return 0;
  if ( $a[$index] < $b[$index] )
     return -1;
  return 1;

这对usort() 是否可行,因为当您调用该函数时,它根本不带参数?还有其他选择吗?

【问题讨论】:

    标签: php usort


    【解决方案1】:

    你可以创建一个类

    class SortRecord
    {
        private $index;
    
        public function __construct($index)
        {
            $this->index = $index;
        }
    
        public function sort_records($a, $b)
        {
            if ( $a[$this->index] == $b[$this->index] )
                return 0;
            if ( $a[$this->index] < $b[$this->index] )
                return -1;
            return 1;
        }
    }
    

    然后您可以将其传递给usort

    $obj = new SortRecord('created_at');
    usort($merged_array, array($obj, 'sort_records'));
    

    【讨论】:

    • 我实际上非常喜欢这个,但其他答案之一更适合我当前的应用程序。
    【解决方案2】:

    usort 放入sort_records 并使用匿名函数,如下所示:

    function sort_records(&$array,$index){
        return usort($array, function ($a, $b) use ($index) {
            if ( $a[$index] == $b[$index] )
                return 0;
            if ( $a[$index] < $b[$index] )
                return -1;
            return 1;
        });
    }
    

    然后你可以用你需要的任何索引来调用它

    sort_records($array, 'created_at');
    

    【讨论】:

      【解决方案3】:

      您也可以在您的 usort 上使用 use 关键字,但您必须将内部函数声明为 anonymous

      function better_usort($array, $index) {
          return usort($array, function($a, $b) use($index){
              if ($a[$index] == $b[$index])
                  return 0;
              if ($a[$index] < $b[$index])
                  return -1;
              return 1;
          });
      }
      

      然后你可以调用它

      better_usort($merged_array, 'created_at');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-01
        • 2012-03-18
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多