2016-11-22 37 views
2

我需要合并,然后排序具有不同数据结构的两个数组(不能在MySQL查询中排序),但其中都有created_on字段。更好的PHP usort()

所以我使用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()当你调用不带参数的所有功能,因为?还有其他选择吗?

回答

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

您可以创建一个类

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')); 
+0

其实我喜欢这个有很多,但其他的答案之一是我当前的应用程序更好地调用它。 – skribe

0

您也可以使用您的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'); 
叫它