PHP multidimensional array Sorting implementation code

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.