【问题标题】:sorting array using two keys, If two values of a key is same then use another key?使用两个键对数组进行排序,如果一个键的两个值相同,那么使用另一个键?
【发布时间】:2014-01-18 05:10:21
【问题描述】:

我有一个 php 数组,其中有两个键在排序时我必须考虑,如果两个用户的计数相同,则考虑这些值的另一个键。

例如。

$result = $client->getTopUsers();
for($i = 0; $i < count($result); $i++)
{

    if($result[$i]['count'] == $result[$i + 1]['count'])
    {
        if($result[$i + 1]['liked'] > $result[$i]['liked'])
        {
            $result[$i + 1]['rank'] = $i-2;
            $result[$i]['rank'] = $i + 1;
        } else
        {
            $result[$i]['rank'] = $i;
        }
    } else
    {
        $result[$i]['rank'] = $i;
    }
    $result[$i]['rank'];
}

在上图中,最后 2 个条目的计数相同,因此我希望我的排名与 like_count 一致。这是我迄今为止尝试过的,但我没有得到预期的结果(“RANK”)。

【问题讨论】:

    标签: php mysql sql select sql-order-by


    【解决方案1】:

    在查询中使用ORDER BY,无需在PHP代码中对数据进行排序,见下例

    SELECT * 
    FROM users u 
    ORDER BY u.count DESC, u.liked_count DESC
    

    它给了我这样的东西,

    【讨论】:

    • 请检查编辑,我希望 like_count 也正常。
    • @RayonDabre 你喜欢count ASC 还是DESC?
    • 点赞数越多的人越高。
    【解决方案2】:

    也许这可以解决你的问题

    select rownum as rnk,field_1,field_2 from (select * from table_name order by key_field1,key_field2 desc limit 10) order by rownum ;
    

    【讨论】:

      【解决方案3】:
      select * 
      from veer_user_details 
      order by count desc, liked_count desc;
      

      这个查询对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 2017-07-15
        • 2023-03-17
        • 2012-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多