对多维数组排序,通用的作法是 1 获取利用排序的数据并且将其放入数组$arrSort. 其中键索引为要排序数组的索引,保证唯一性 2 利用排序函数sort等对$arrSort进行排序. 3 遍历$arrSort,根据其索引,获取多维数组的数据,重新构造排序后的多维数组. <div class="codetitle"><a style="CURSOR: pointer" data="66823" class="copybut" id="copybut66823" onclick="doCopy('code66823')"> 代码如下:<div class="codebody" id="code66823"> Array ( [0] => Array ( [link] => test [name] => test.rpm [type] => file [size] => 988.9k [mtime] => 1185160178) .... )
I 很久以前在网上找到的一个排序函数,谈不上高效,但很实用 <div class="codetitle"><a style="CURSOR: pointer" data="58538" class="copybut" id="copybut58538" onclick="doCopy('code58538')"> 代码如下:<div class="codebody" id="code58538"> _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; }
II 用array_map和array_mutisort来排序 array_mutisort还可以根据多个值来进行二次或者三次排序,这是上一个函数所不能比的. <div class="codetitle"><a style="CURSOR: pointer" data="36511" class="copybut" id="copybut36511" onclick="doCopy('code36511')"> 代码如下:<div class="codebody" id="code36511"> 利用array_map获取要依据排序的数组 $arrField = array_map(create_function('$n','return $n["size"];'),$arrFile); //利用array_mutisort来进行排序 $array_multisort($arrField,SORT_DESC,$arrFile);
III 最终测试 以188条数据的数组进行测试,排序50次求平均值. 第一种方式 0.04269016 name 0.04267142 size 第二种方式 0.001249 name 0.00083924 size 结果不言而喻 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|