phparrayssortingmultidimensional-array

Sort an array of single-element arrays by value descending and preserve keys


How to sort a multidimensional array by value?

I have data like this:

$num_a = $_POST['num_a']; //get the value data by array num_a[]
$num_b = $_POST['num_b']; //get the value data by array num_b[]
$score = $_POST['score']; //get the value data by array socre[]

for ($i=0; $i < count($num_a); $i++) { 
    //set total data num_a and num_b with value from score
    $ring[($num_a[$i])][($num_b[$i])] = $score[$i]; 
}

print_r($ring);
//output

Array
(
    [0] => Array
        (
            [1] => 5
        )
    [1] => Array
        (
            [2] => 1
        )
    [2] => Array
        (
            [0] => 3
        )
)

How can I display the results sorted by desc, so the results are like this:

Array
(
    [0] => Array
        (
            [1] => 5
        )
    [2] => Array
        (
            [0] => 3
        )
    [1] => Array
        (
            [2] => 1
        )
)

Solution

  • You can also use array_multisort (PHP 4, PHP 5)

    array_multisort(
                     array_map(function($_){return reset($_);},$ring), 
                     SORT_DESC, 
                     $ring
                   );
    

    Test

    [akshay@localhost tmp]$ cat test.php 
    <?php
    
    $data = array(
       array( 1 => 5),
       array( 2 => 1),
       array( 0 => 3),        
    );
    
    // Input
    print_r($data);
    
    // Sort DESC
    array_multisort(array_map(function($_){return reset($_);},$data), SORT_DESC, $data); 
    
    // Output - sorted array
    print_r($data);
    
    ?>
    

    Output

    [akshay@localhost tmp]$ php test.php 
    Array
    (
        [0] => Array
            (
                [1] => 5
            )
    
        [1] => Array
            (
                [2] => 1
            )
    
        [2] => Array
            (
                [0] => 3
            )
    
    )
    Array
    (
        [0] => Array
            (
                [1] => 5
            )
    
        [1] => Array
            (
                [0] => 3
            )
    
        [2] => Array
            (
                [2] => 1
            )
    
    )