本文章给大家整一个php 多维数组的排序实现代码,我们在实际编码中将会用到PHP函数array_multisort()来实现这一复杂的排序,有需要了解的朋友可参考。
<script>ec(2);</script>
如数组
代码如下 |
复制代码 |
Array
(
[0] => Array
(
[id] => 1146
[orderid] => 3
)
[1] => Array
(
[id] => 1149
[orderid] => 2
)
[2] => Array
(
[id] => 170
[orderid] => 4
)
[3] => Array
(
[id] => 1121
[orderid] => 3
)
[4] => Array
(
[id] => 1120
[orderid] => 7
)
)
|
这么一个数据,想按orderid来排序。找不到内置的php函数,网上搜索了下,发现如下方法:
代码如下 |
复制代码 |
$asc_func = create_function('$a,$b','
$k = "orderid";
if($a[$k] == $b[$k]) return 0;
return $a[$k]>$b[$k]?1:-1;
');
usort($arrs,$asc_func);
|
$arrs是原数组,$k="orderid"是要排序的字段
后来对上面代码进行了升级
代码如下 |
复制代码 |
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
if(!is_array($ArrayData))
{
return $ArrayData;
}
// Get args number.
$ArgCount = func_num_args();
// Get keys to sort by and put them to SortRule array.
for($I = 1;$I
{
$Arg = func_get_arg($I);
if(!eregi("SORT",$Arg))
{
$KeyNameList[] = $Arg;
$SortRule[] = '$'.$Arg;
}
else
{
$SortRule[] = $Arg;
}
}
// Get the values according to the keys and put them to array.
foreach($ArrayData AS $Key => $Info)
{
foreach($KeyNameList AS $KeyName)
{
${$KeyName}[$Key] = $Info[$KeyName];
}
}
// Create the eval string and eval it.
$EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
eval ($EvalString);
return $ArrayData;
}
|