Several methods of sorting two-dimensional arrays in php_PHP tutorial

WBOY
Release: 2016-07-13 10:43:42
Original
857 people have browsed it

Two-dimensional array sorting also provides a function array_multisort in PHP that can be sorted directly. Below I will introduce that in addition to using array_multisort to sort arrays, we have also written some custom two-dimensional array sorting methods.

Sometimes, in order to achieve a certain purpose, it is necessary to sort a two-dimensional array. Now I will share how to achieve it.

The code is as follows Copy code
 代码如下 复制代码

$arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 5 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 3 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
 )  ; $result = sysSortArray($arr,'num');这样运行之后的效果为:

$arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 3 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 5 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
 )  ;用到的函数:

/**
 * @package     二维数组排序
 * @version     $Id: FunctionsMain.inc.php,v 1.32 2011/09/24 11:38:37 wwccss Exp $
 *
 *
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2";……)
 * @author                      lamp100
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by("SORT_ASC"|"SORT_DESC")
 * @param  string  $SortType1   the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
 * @return array                sorted array.
 */
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 < $ArgCount;$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;
}

$arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 5 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 3 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
) ; $result = sysSortArray($arr,'num'); The effect after running like this is: $arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 3 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 5 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
) ; Functions used: /**
 * @package     二维数组排序
 * @version     $Id: FunctionsMain.inc.php,v 1.32 2011/09/24 11:38:37 wwccss Exp $
 *
 *
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2";……)
 * @author                      lamp100
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by("SORT_ASC"|"SORT_DESC")
 * @param  string  $SortType1   the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
 * @return array                sorted array.
 */
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 < $ArgCount;$I ++)
{
          $Arg = func_get_arg($I);
If(!eregi("SORT",$Arg))
                                  {
               $KeyNameList[] = $Arg;
$SortRule[] = '$'.$Arg;
         }
         else
                                  {
              $SortRule[]                                                                                                                                                                                                     }
}<🎜> <🎜> // 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;
}

In addition: the array_multisort function is also very powerful. For details, please refer to the PHP manual, which is very detailed.


We can use the array_multisort() function. The array_multisort() function sorts multiple arrays or multidimensional arrays.

The array in the parameter is treated as a table column and sorted by row - this is similar to the functionality of SQL's ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array compare to be the same, they will be sorted according to the size of the corresponding value in the next input array, and so on.

The first parameter is an array, and each subsequent parameter may be an array or one of the following sort order flags (the sort flag is used to change the default sort order):

•SORT_ASC - Default, sort in ascending order. (A-Z)
•SORT_DESC - Sort in descending order. (Z-A)
You can then specify the sorting type:

•SORT_REGULAR - Default. Arrange each item in regular order.
•SORT_NUMERIC - Sort each item in numerical order.
•SORT_STRING - Sort each item in alphabetical order.
Syntax: array_multisort(array1,sorting order,sorting type,array2,array3...)

•array1: required. Specifies the input array.
•Sort order: optional. Specify the order of sorting. Possible values ​​are SORT_ASC and SORT_DESC.
•sorting type: optional. Specifies the sorting type. Possible values ​​are SORT_REGULAR, SORT_NUMERIC, and SORT_STRING.
•array2: optional. Specifies the input array.
•array3: optional. Specifies the input array.
String key names will be preserved, but numeric keys will be re-indexed, starting at 0 and increasing by 1. The sort order and sort type can be set after each array. If not set, each array parameter will use its default value.

Here is an example:

The code is as follows Copy code
 代码如下 复制代码


$arr = '';

echo '二维数组如下:'.'
';
 for($i=0; $i<=5; $i++)
{
$arr[$i]['val'] = mt_rand(1, 100);
$arr[$i]['num'] = mt_rand(1, 100);
}

echo '

';<br>
 print_r($arr);<br>
 echo '
';
 
 echo '从二维数组中抽出键为val,单独成另一个数组:'.'
';
 foreach ($arr as $key => $row)
 {
     $vals[$key] = $row['val'];
        $nums[$key] = $row['num'];
 }
 
 echo '
';<br>
 print_r($vals);<br>
 echo '
';
 
 echo '对其进行排序:'.'
';
 array_multisort($vals, SORT_ASC, $arr);
 
 echo '
';<br>
 print_r($vals);<br>
 echo '
';
 
?>

'; for($i=0; $i<=5; $i++) { $arr[$i]['val'] = mt_rand(1, 100); $arr[$i]['num'] = mt_rand(1, 100); } echo '
';
print_r($arr);
echo '
'; echo 'Extract the key val from the two-dimensional array and separate it into another array:'.'
'; foreach ($arr as $key => $row) { $vals[$key] = $row['val'];           $nums[$key] = $row['num']; } echo '
';
print_r($vals);
echo '
'; echo 'Sort it:'.'
'; array_multisort($vals, SORT_ASC, $arr); echo '
';
print_r($vals);
echo '
'; ?>

Run result:

The two-dimensional array is as follows:
Array
(
[0] => Array
(
                                                                                                                                [val] =>                                                                                           [num] => 49
)

[1] => Array

(
                                                                                                                                    [val] =>                                                                                                           [num] => )

[2] => Array
(

                                                                                                                                                                                                    [val] =>                                                                                           [num] => 3

)

[3] => Array
(
                                                                                                                                                                                                                  [val] =>                                                                                                             [num] => )

[4] => Array
(
                                                                                                                [val] => 19
                                                                                                                [num] => )

[5] => Array

(
                                                                                                                          [val] =>                                                                                                             [num] => )

)
Extract the key val from the two-dimensional array and separate it into another array:

Array

(
[0] => 46
[1] => 8
[2] => 37
[3] => 32

[4] => 19

[5] => 30
)
Sort it:
Array
(
[0] => 8
[1] => 19
[2] => 30
[3] => 32
[4] => 37
[5] => 46
)

We will get a two-dimensional array sorted by val in ascending order.






http://www.bkjia.com/PHPjc/633146.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633146.html

TechArticleTwo-dimensional array sorting. PHP also provides a function array_multisort that can be sorted directly. I will introduce it below. In addition to completely using array_multisort to sort the array we also wrote...
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