2014-09-07 31 views
0

如何從表格中選擇前40個數據(基於amount),然後找到特定用戶放置在該數據組中的位置?PHP - 如何從查詢中獲取訂單並獲取「地點編號」

實施例,我選擇頂部40中的數據:

if($userdata['forum_moderator'] == 1){ 
$c = $dbh->prepare("SELECT * FROM referral_competition ORDER BY amount DESC LIMIT 5"); 
$c->execute(); 

$competition = $c->fetchAll(); 

    echo "<pre>"; 
    var_dump($competition); 
    echo "</pre>"; 

這給了我:

[0]=> 
array(2) { 
    ["userid"]=> 
    string(1) "1" 
    [0]=> 
    string(1) "1" 
    ["amount"]=> 
    string(2) "14" 
    [0]=> 
    string(2) "14" 
    } 
[1]=> 
array(2) { 
    ["userid"]=> 
    string(1) "5" 
    [0]=> 
    string(1) "1" 
    ["amount"]=> 
    string(2) "10" 
    [0]=> 
    string(2) "10" 
    } 
[2]=> 
array(2) { 
    ["userid"]=> 
    string(1) "4" 
    [0]=> 
    string(1) "1" 
    ["amount"]=> 
    string(2) "8" 
    [0]=> 
    string(2) "8" 
    } 
[3]=> 
array(2) { 
    ["userid"]=> 
    string(1) "9" 
    [0]=> 
    string(1) "1" 
    ["amount"]=> 
    string(2) "3" 
    [0]=> 
    string(2) "3" 
    } 
etc. etc. 

如何可以找出一特定的用戶被置於上方的陣列中,基於所述用戶ID?

例子:

您放置number 3,你有amount: 8

+0

爲什麼不簡單地使用$ competition的數組鍵並添加1? – VMai

+0

「加1」是什麼意思?你能舉個例子嗎? – oliverbj

+0

用戶名爲4的用戶是$ competition [2]的元素,因此她將數字2 + 1 = 3 ... – VMai

回答

1

在內部選擇獲得前40和排名列添加到它。另一個select只獲取特定用戶的等級和數量。

select amount, rank 
from 
(
    SELECT *, @rank := @rank + 1 as rank 
    FROM referral_competition 
    CROSS JOIN (select @rank := 0) r 
    ORDER BY amount DESC 
    LIMIT 40 
) tmp 
where userid = $someUser 
+0

謝謝,它現在顯示正確的「順序」,當我做var_dump()。雖然,當我嘗試回顯它時:<?php echo $ competition [「rank」]; ?>什麼都沒有顯示。 – oliverbj

+0

對不起,我幫不了你。這似乎是一個PHP問題,我不是專家。 –

0

此解決方案不要求您更改已擁有的sql查詢。它還使您可以快速訪問用戶數據。

$ordered = []; 
    foreach($competition as $k=>$result) { 
    $rank = $k + 1; //Add plus one as the indexed resultset starts from zero 
    $user_id = $result['userid']; //Grab the user id 
    $ordered[$user_id]=$result; //Little trick to add the user id as the array index key 
    $ordered[$user_id]['rank']=$rank; //Add the rank as new array element 
    } 

    //Now you can get any user record out of the array by using the userid as key 

    //Example: 
    $user = $ordered[3]; 
    $rank = $user['rank'];