Home > Backend Development > PHP Tutorial > php array_map array_multisort 高效处理多维数组排序_php技巧

php array_map array_multisort 高效处理多维数组排序_php技巧

WBOY
Release: 2016-05-17 09:32:12
Original
823 people have browsed it

对多维数组排序,通用的作法是
1 获取利用排序的数据并且将其放入数组$arrSort. 其中键索引为要排序数组的索引,保证唯一性
2 利用排序函数sort等对$arrSort进行排序.
3 遍历$arrSort, 根据其索引,获取多维数组的数据,重新构造排序后的多维数组.

复制代码 代码如下:

Array
(
[0] => Array
(
[link] => test
[name] => test.rpm
[type] => file
[size] => 988.9k
[mtime] => 1185160178)
....
)

I 很久以前在网上找到的一个排序函数,谈不上高效,但很实用
复制代码 代码如下:

_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还可以根据多个值来进行二次或者三次排序,这是上一个函数所不能比的.
复制代码 代码如下:

利用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

结果不言而喻
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template