Array of arrays
| The code is as follows |
Copy Code |
|
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
)
)
|
Such a data, want to press OrderID to sort. Could not find the built-in PHP function, search the Internet, found the following methods:
| The code is as follows |
Copy Code |
|
$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 is the original array, $k = "OrderID" is the field to sort
Later, the code was upgraded
| The code is as follows |
Copy Code |
|
function Syssortarray ($ArrayData, $KeyName 1, $SortOrder 1 = "Sort_asc", $SortType 1 = "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 < $ArgCount; $I + +)
{
& nbsp; $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;
}
|