-
-
- array_sort($arrFile, 1, 1);//Sort according to the name field
- array_sort($arrFile, 3, 1);//Sort according to the size field
- / *
- @records Array to be sorted
- @field Field to be sorted, pay attention to whether it is a number
- @reverse positive or negative order
- */
- 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;
- }
-
Copy code
2. Use array_map and arra y_mutisort to sort
array_mutisor can also perform secondary or triple sorting based on multiple values, which is incomparable to the previous function.
Use array_map to get the array to be sorted by
$arrField = array_map(create_function('$n', 'return $n["size"];'), $arrFile);
//Use array_mutisort to sort
$array_multisort($arrField, SORT_DESC, $arrFile);
3. Final test
Test with an array of 188 data, sort 50 times and find the average.
Way 1:
0.04269016 name
0.04267142 size
Method 2:
0.001249 name
0.00083924 size
>>> For more information, please view the complete list of php array sorting methods
|