array_sort($arrFile, 1, 1);//根據name欄位排序
- array_sort($arrFile, 3, 1);//根據size欄位排序
- /*
- @records 要排序的數組
- @field要排序的欄位,注意是數字
- @reverse正序還是反序
- */
- function _array_sort($records, $field, $reverse, $defaultSortField = 0)
- {
- $uniqueSortId = 0;
- $hash = array();
- $sortedRecords = array();
- $tempArr = array();
- $indexedArray = array();
- $recordArray = array();
foreach($records as $record)
- {
- $uniqueSortId++;
- $recordStr = implode("|", $record)."|".$uniqueSortId;
- $recordArray[] = explode("|", $recordStr);
- }
$primarySortIndex = count($record);
- $records = $recordArray;
foreach($records as $record)
- {
- $hash[$record[$primarySortIndex]] = $record[$field];
- }
- uasort($hash, "strnatcasecmp");
- if($reverse)
- $hash = array_reverse($hash, true);
$valueCount = array_count_values($hash);
foreach($hash as $primaryKey => $value)
- {
- $indexedArray[] = $primaryKey;
- }
$i = 0;
- foreach($hash as $primaryKey => $value)
- {
- $i++;
- if($valueCount[$value] > 1)
- {
- foreach($records as $record)
- {
- if($primaryKey == $record[$primarySortIndex])
- {
- $tempArr[$record[$defaultSortField]."__".$i] = $record;
- break;
- }
- }
$index = array_search($primaryKey, $indexedArray);
if(($i == count($records)) || ($value != $hash[$indexedArray[$index+1]]))
- {
- uksort($tempArr, "strnatcasecmp");
if($reverse)
- $tempArr = array_reverse($tempArr);
foreach($tempArr as $newRecs)
- {
- $sortedRecords [] = $newRecs;
- }
$tempArr = array();
- }
- }
- else
- {
- foreach($records as $record)
- {
- if($primaryKey == $record[$primarySortIndex])
- {
- $sortedRecords[] = $record;
- break;
- }
- }
- }
- }
- return $sortedRecords;
- }
複製代碼2、用array_map和array_mutisort來排序 array_mutisort還可以根據多個值來進行二次或者三次排序,這是上一個函數所不能比的。利用array_map擷取要依據排序的數組 $arrField = array_map(create_function('$n', 'return $n["size"];'), $arrFile); //利用array_mutisort來進行排序 $array_multisort($arrField, SORT_DESC, $arrFile); 3、最終測試 以188條資料的數組進行測試, 排序50次求平均值. 方式1: 0.04269016 name 0.04267142 size 方式2: 0.001249 name 0.00083924 size >>> 更多內容,請查看 php數組排序方法大全 <<< |