3

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
        )
)
3
  • 1
    Will the array children always be arrays of one element? If so, why are they arrays and not just numbers? Commented Jul 8, 2015 at 1:51
  • i want to sorting by the values of array. Commented Jul 8, 2015 at 3:01
  • 1
    Understand but you aren't answering my question. Do the arrays will only contain one value? Commented Jul 8, 2015 at 3:05

2 Answers 2

1

Try this

$data = [
    0 => [ 1 => 5],
    1 => [ 2 => 1],
    2 => [ 0 => 3],        
];
uasort($data, function($a, $b) {
    $a = array_pop($a);
    $b = array_pop($b);
    if ($a == $b)
    {
        return 0;    
    }
    return ($a < $b) ? 1 : -1;
});

var_dump($data);
Sign up to request clarification or add additional context in comments.

Comments

0

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
        )

)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.