2016-11-22 3 views
2

나는 병합 후 서로 다른 데이터 구조 (MySQL 쿼리에서 정렬 할 수없는) 두 배열을 정렬해야하지만 둘 다 created_on 필드를했다.더 나은 PHP는 usort()

그래서 사용자 정의 기능과 함께 usort()을 사용하고 있습니다. 내 도우미 기능

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; 
    } 
} 

에서 내 컨트롤러

usort(merged_array, 'sort_records'); 

에서

나는이 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

usortsort_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'); 
로 호출 할 수 있습니다