2016-11-22 38 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'); 
叫它