2010-09-16 33 views
0

usort uasort使用比較函數,因爲每次需要在數組元素之間進行比較時必須計算它,所以比較函數很慢。其他語言(如Python)允許您使用一個鍵值函數對數組進行排序,該函數僅在數組中的每個元素上評估一次。在PHP中執行此操作的最佳方法是什麼?使用按鍵功能在PHP中排序數組的最佳方法?

+1

這傢伙也[他的網站上寫博客這個問題(http://www.nathanieltroutman.net/content/sorting-arrays-php-using-key-function)。它有更多的細節和基準測試結果。 – shamittomar 2010-09-16 20:05:03

回答

-3
 
function sort_with_keyfunc($array, $keyfunc) { 
    $keys = array_map($keyfunc, $array); // get the keys for each item 
    array_multisort($keys, $array); // sort $array according to the sorted keys 
    return $array; 
} 

這也在關聯數組中維護key =>值對。

+3

呃whaaaaat?你立即回答你自己的問題 - 在不到兩分鐘內? – Rudu 2010-09-16 19:53:12

+0

它是一個很好的快速方法來獲得這些徽章:) – 2010-09-16 19:55:50

+0

這傢伙也是[在他的網站上關於這個問題的博客](http://www.nathanieltroutman.net/content/sorting-arrays-php-using-key-function )。它有更多的細節和基準測試結果。 – shamittomar 2010-09-16 20:05:50

0

你需要更快?使用Quicksort

<?php 
function quicksort($arr, $l = 0 , $r = NULL) { 
// when the call is recursive we need to change 
// the array passed to the function earlier 
    static $list = array(); 
    if($r == NULL) 
     $list = $arr; 

    if($r == NULL) 
     $r = count($list)-1;//last element of the array 

    $i = $l; 
    $j = $r; 

    $tmp = $list[(int)(($l+$r)/2)]; 

    // partion the array in two parts. 
    // left from $tmp are with smaller values, 
    // right from $tmp are with bigger ones 
    do { 
     while($list[$i] < $tmp) 
      $i++; 

     while($tmp < $list[$j]) 
      $j--; 

     // swap elements from the two sides 
     if($i <= $j) { 
      $w = $list[$i]; 
      $list[$i] = $list[$j]; 
      $list[$j] = $w; 

      $i++; 
      $j--; 
     } 
    }while($i <= $j); 

    // devide left side if it is longer the 1 element 
    if($l < $j) 
     quicksort(NULL, $l, $j); 

    // the same with the right side 
    if($i < $r) 
     quicksort(NULL, $i, $r); 

    // when all partitions have one element 
    // the array is sorted 

    return $list; 
} 
?> 
+1

ee gads man,使用這樣的短標籤! EEEK! (注意,我現在感覺違反了) – 2010-09-16 19:56:19

+2

-1 [PHP的sort函數](http://php.net/sort)已經在使用Quicksort了:「和大多數PHP的排序函數一樣,sort()使用一個實現Quicksort。「 – Gumbo 2010-09-16 20:00:29

+0

@Gumbo:不錯的一點。我從未注意到這一點。 :) – shamittomar 2010-09-16 20:01:39