2016-05-09 74 views
-1

我有一個MySQL數據庫中有一個表(1-10),並有一個XP_NEEDED列的表,我已經有一個數字,我想從該數字(數字是XP)中找到關卡,我知道如何在下面的方式做到這一點...如何從XP獲得正確的行?

Example (Short): 
if ($xpLookingFor >= 100 && $xpLookingFor < 200) // Checks if not high as level 2 { 
    return '1'; // Would be returning Level1 
} 
else if ($xpLookingFor >= 200 && $xpLookingFor < 300) // Checks if not high as level 3 { 
    return '2'; // Would be returning Level2 
} 

所以它會檢查其是否比當前水平高,但沒有那麼高的水平aboves xp_needed,如果其高達下一級別的下一個如果聲明將處理它。

但是這種方式有很多可能縮短的代碼,最好的方法是什麼?有沒有一個內置的mysql功能?

+0

您有[問題數量](http://stackoverflow.com/users/6276855/thegod39)在這裏回答良好但未標記爲已解決。在適用的時候,請開始標記答案,否則你會有很多人幫助你而不提供任何回報。如果您不知道如何執行此操作,請參閱[this](http://stackoverflow.com/help/someone-answers)。 – camelCase

回答

0

因爲您使用的是elseif,所以if的第一部分不需要,您可以將它們堆疊在一起。

function getLevel($xpLookingFor){ 
    if ($xpLookingFor < 100){ 
     return 0; 
    } 
    else if ($xpLookingFor < 200){ 
     return 1; 
    } 
    else if ($xpLookingFor < 300){ 
     return 2; 
    } 
    else if ($xpLookingFor < 375){ 
     return 3; 
    } 
    else if ($xpLookingFor < 400){ 
     return 4; 
    } 
    else { 
     return 'MAX!'; 
    } 
} 

See example on IdeOne

2

林不知道這是否是你所需要的問題不是太清楚。

<?php 
function getLevel($xp, $maxLevel) { 
    for($check = 1; $check < $maxLevel; $check++) 
     if ($xp >= ($check*100) AND $xp < ($check*100)+100) return $check; 
    return $maxLevel; 
} 

//Param #1 is the xp level and #2 is the max level 
echo getLevel(503, 10); // returns 5 
echo getLevel(123, 10); //returns 1 
echo getLevel(1405, 20); //returns 14 
echo getLevel(1405, 10); //returns 10 
?> 
+0

好的解決方案+1,唯一的問題是如果每個級別都不是100的倍數,這是行不通的,但是從這個問題來看還不清楚是不是這種情況。 –