PHP排序数组2值

时间:2017-10-08 10:37:40

标签: php sorting

我需要对“时间”和“checkdanum”进行排序 对于第一次排序(时间),它起作用 但是第二次排序(checkdanum),它不起作用。

它返回我需要
50-3的 77-3
77-3的 50-3
46-3 46-3
84-2 84-2
74-2 74-2
74-2 74-2
48-2 48-2
75-1 75-1
70-1 70-1
46-1 46-1

请帮忙。

<?php

$dbx['x1']['inplay']['time'] = 84;
$dbx['x2']['inplay']['time'] = 77;
$dbx['x3']['inplay']['time'] = 75;
$dbx['x4']['inplay']['time'] = 74;
$dbx['x5']['inplay']['time'] = 74;
$dbx['x6']['inplay']['time'] = 70;
$dbx['x7']['inplay']['time'] = 50;
$dbx['x8']['inplay']['time'] = 48;
$dbx['x9']['inplay']['time'] = 46;
$dbx['x10']['inplay']['time'] = 46;

$dbx['x1']['inplay']['checkdanum'] = 2;
$dbx['x2']['inplay']['checkdanum'] = 3;
$dbx['x3']['inplay']['checkdanum'] = 1;
$dbx['x4']['inplay']['checkdanum'] = 2;
$dbx['x5']['inplay']['checkdanum'] = 2;
$dbx['x6']['inplay']['checkdanum'] = 1;
$dbx['x7']['inplay']['checkdanum'] = 3;
$dbx['x8']['inplay']['checkdanum'] = 2;
$dbx['x9']['inplay']['checkdanum'] = 3;
$dbx['x10']['inplay']['checkdanum'] = 1;



$dbx = desc_sort($dbx , 'time');

$dbx = desc_sort($dbx,'checkdanum');
echo '<pre>';
foreach($dbx as $k => $v){
echo $dbx[$k]['inplay']['time'].'-'.$dbx[$k]['inplay']['checkdanum'].'<br>';
}

function desc_sort ($array, $key) {
    $sorter = array();
    $ret = array();
    reset($array);
    foreach ($array as $ii => $va) {
        foreach ($array[$ii] as $k => $v){
            if($k == 'inplay'){
            $sorter[$ii] = $v[$key];
            }
        }
    }

    if (!function_exists('myComparison')) {
        function myComparison($a, $b){
            if(is_numeric($a) && !is_numeric($b))
            return -1;
            else if(!is_numeric($a) && is_numeric($b))
            return 1;
            else
            return ($a < $b) ? 1 : -1;
        }
    }

    uasort ( $sorter , 'myComparison' );
    foreach ($sorter as $ii => $va) {
        $ret[$ii] = $array[$ii];
    }
    return $ret;
}

1 个答案:

答案 0 :(得分:0)

您可以同时对两者进行排序。如果您使用的是PHP 7+,则可以通过spaceship operator保存一些比较。例如:

<?php   
uasort($dbx, function ($x,$y) {
   if (($x["inplay"]["checkdanum"] <=> $y["inplay"]["checkdanum"]) === 0) {
       return -($x["inplay"]["time"] <=> $y["inplay"]["time"]);
   } 
   return -($x["inplay"]["checkdanum"] <=> $y["inplay"]["checkdanum"]);
});

这个seems to work并且非常简化。

对于较旧的PHP版本,您可以回退到您定义为“myComparison”的函数。

注意:您可以通过检查索引是否存在来填充此内容