How to sort array data by value?
how to sort multiple arrays 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 to display the results sort ed desc so the results look like this, thanks
the output i want
print_r ($ ring);
Array
(
[0] => Array
(
[1] => 5
)
[2] => Array
(
[0] => 3
)
[1] => Array
(
[2] => 1
)
)
+3
source to share
2 answers
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
)
)
0
source to share