-
-
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数组排序方法大全
|