usort和 uasort使用比較函數,因爲每次需要在數組元素之間進行比較時必須計算它,所以比較函數很慢。其他語言(如Python)允許您使用一個鍵值函數對數組進行排序,該函數僅在數組中的每個元素上評估一次。在PHP中執行此操作的最佳方法是什麼?使用按鍵功能在PHP中排序數組的最佳方法?
回答
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 =>值對。
呃whaaaaat?你立即回答你自己的問題 - 在不到兩分鐘內? – Rudu 2010-09-16 19:53:12
它是一個很好的快速方法來獲得這些徽章:) – 2010-09-16 19:55:50
這傢伙也是[在他的網站上關於這個問題的博客](http://www.nathanieltroutman.net/content/sorting-arrays-php-using-key-function )。它有更多的細節和基準測試結果。 – shamittomar 2010-09-16 20:05:50
你需要更快?使用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;
}
?>
ee gads man,使用這樣的短標籤! EEEK! (注意,我現在感覺違反了) – 2010-09-16 19:56:19
-1 [PHP的sort函數](http://php.net/sort)已經在使用Quicksort了:「和大多數PHP的排序函數一樣,sort()使用一個實現Quicksort。「 – Gumbo 2010-09-16 20:00:29
@Gumbo:不錯的一點。我從未注意到這一點。 :) – shamittomar 2010-09-16 20:01:39
- 1. 最佳的排序方式在PHP的鍵多維數組
- 2. 在PHP中對數組進行排序的最佳方法
- 3. php按數組鍵排序
- 4. 排序2d數組的最佳方法Php
- 5. PHP排序多維數組的最佳方法?
- 6. 排序數組而不使用排序功能在PHP
- 7. 使用靜態類方法*快速*按PHP中的鍵值排序數組
- 8. 使用排序功能按NSDates對數組排序
- 9. php - 按數組中最後一個鍵的值排序?
- 10. 無法按照鍵值對數組進行排序使用PHP
- 11. 最佳功能方法
- 12. 最佳的排序方式在PHP
- 13. 用PHP/MySQL緩存已排序數據的最佳方法
- 14. 通用功能的最佳方法
- 15. 用中間最長的字符串排序數組的最佳方法
- 16. 按鍵號排序數組PHP
- 17. 多維數組按鍵值排序PHP
- 18. 用鍵存儲數組的最佳方法,並按條目順序對它們進行排序
- 19. 對數組進行排序的最佳方法
- 20. 排序2個數組列表的最佳方法?
- 21. 在php中使用這個數組循環的最佳方式
- 22. 按值排序數組鍵
- 23. 按鍵排序數組
- 24. 檢測被按下的功能鍵的最佳方法是什麼?
- 25. 按排序排序的PHP數組
- 26. 在我的排序功能中顯示最佳結果
- 27. 獲取按各自鍵排序的哈希值的最佳方法? (紅寶石)
- 28. 排序viewcontrollers/xibs的最佳方法?
- 29. 排序NSMutableArray的最佳方法?
- 30. 使用C中的子程序排序並行數組的最佳或最有效的方法?
這傢伙也[他的網站上寫博客這個問題(http://www.nathanieltroutman.net/content/sorting-arrays-php-using-key-function)。它有更多的細節和基準測試結果。 – shamittomar 2010-09-16 20:05:03