2014-01-18 68 views
1

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

Ex。 Table structure for example

$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项的数量是相同的,所以我想我根据排名liked_count.This是我到目前为止已经试过,但我没有得到的结果(“等级”)作为预期。

回答

1

使用ORDER BY在查询,没有必要在PHP代码中的数据进行排序,参见下面的例子

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

它给了我这样的事情,Result

+0

请检查编辑内容,我也想按照顺序排列。 – Rayon

+0

@RayonDabre你是否赞成计算ASC或DESC? –

+0

获得更多喜欢的人将会处于更高层次。 – Rayon

0

可能是这样可以解决您的问题

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 ; 
0
select * 
from veer_user_details 
order by count desc, liked_count desc; 

这个查询WO为我而去。

相关问题