如何按值数据排序多个数组



如何按值排序多数组?我有这样的数据

$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
        )
)

如何显示结果sorted by desc,所以结果是这样的,谢谢

我想要的输出

print_r(环);

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

试试这个

$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);

也可以使用array_multisort (php4, php5)

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

[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);
?>

[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
        )
)

相关内容

  • 没有找到相关文章

最新更新