A simple example of php sorting two dimensional arrays

  • 2020-11-30 08:12:04
  • OfStack

In this article, php USES the array_multisort function to sort 2-dimensional arrays. If you need it, please refer to it. Following on from the previous article: PHP2-dimensional array sorting custom function, today we will introduce an example of php2-dimensional array sorting.
The sorting of 2-dimensional arrays by php is simple, using the array_multisort function.
Example:


<?php 
/** 
* php2 Dimensional array sort  
* edit www.ofstack.com
*/ 
    $data = array(); 
    $data[] = array('volume' => 67, 'edition' => 2); 
    $data[] = array('volume' => 86, 'edition' => 1); 
    $data[] = array('volume' => 85, 'edition' => 6); 
    $data[] = array('volume' => 98, 'edition' => 2); 
    $data[] = array('volume' => 86, 'edition' => 6); 
    $data[] = array('volume' => 67, 'edition' => 7); 
    //  Gets a list of columns  
    foreach ($data as $key => $row) 
    { 
        $volume[$key]  = $row['volume']; 
        $edition[$key] = $row['edition']; 
    } 
    array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data); 
    print_r($data); 
?> 

Output results:


Array
    (
        [0] => Array
            (
                [volume] => 98
                [edition] => 2
            )
        [1] => Array
            (
                [volume] => 86
                [edition] => 1
            )
        [2] => Array
            (
                [volume] => 86
                [edition] => 6
            )
        [3] => Array
            (
                [volume] => 85
                [edition] => 6
            )
        [4] => Array
            (
                [volume] => 67
                [edition] => 2
            )
        [5] => Array
            (
                [volume] => 67
                [edition] => 7
            )
    )

Description:
The parameters of the array_multisort function are very flexible, so you can refer to the instructions in the php manual for further study.


Related articles: