我需要合并并排序两个具有不同数据结构的数组(不能在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()中是可能的吗,因为当您调用该函数时,它根本不接受参数?还有别的选择吗?
发布于 2016-11-22 13:31:50
将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');发布于 2016-11-22 13:24:21
可以创建一个类
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'));发布于 2016-11-22 13:28:26
您也可以在usort上使用use关键字,但是您必须将内部函数声明为匿名:
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');https://stackoverflow.com/questions/40742942
复制相似问题