【问题标题】:PHP uasort - sort by two keys [duplicate]PHP uasort - 按两个键排序[重复]
【发布时间】:2013-10-29 22:22:48
【问题描述】:

我有一个数组

$DATA = array(
array(
    "id" => "23",
    "rate" => "4.555"
),
array(
    "id" => "12",
    "rate" => "4.555"
),
array(
    "id" => "20",
    "rate" => "4.555"
),

array(
    "id" => "29",
    "rate" => 5.1025"
)   
);

现在我需要按键对上面的数组进行排序:rate(升序)和 id(升序)。

所以:

    function mySort($a, $b) {

      return strcmp($a['rate'], $b['rate']); 

    } 

uasort($DATA,'mySort');

现在排序完美,但仅按比率....

添加新功能:

function mysortID ($a,$b){ //AD
        return ($a['id'] > $b['id']) ? 1 : -1;  
    }

让我们试试吧:

 uasort($DATA,'mySort');
 uasort($DATA,'mySortID');

但不起作用....怎么办?

【问题讨论】:

  • 这个问题现在可以删除了,所以它不会妨碍许多其他重复。

标签: php arrays sorting


【解决方案1】:
function mySort($a, $b)
{
    // Check the rates
    $res = strcmp($a['rate'], $b['rate']);

    // If the rates are the same...
    if ($res === 0) {
        // Then compare by id
        $res = $a['id'] > $b['id'] ? 1 : -1;
    }

    return $res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2011-05-20
    • 2018-11-11
    • 2020-10-04
    • 2012-02-19
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多