douxing5199 2015-08-07 07:09
浏览 34
已采纳

改为使用数组重写PHP函数

Is there any way I could rewrite this function with an array instead of all these if statements? Could i maybe use some for loop together with an array? How would that look like? Any suggestions of simpler code?

Here is my php function:

function to_next_level($point) {

    /*
    **********************************************************************
    *
    *   This function check how much points user has achievents and how much procent it is until next level
    *
    **********************************************************************
    */

    $firstlevel = "3000";
    $secondlevel = "7000";
    $thirdlevel = "15000";
    $forthlevel = "28000";
    $fifthlevel = "45000";
    $sixthlevel = "80000"; 

    if($point <= $firstlevel) {

        $total = ($point/$firstlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;

    } elseif ($point <= $secondlevel) {

        $total = ($point/$secondlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $thirdlevel) {

        $total = ($point/$thirdlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $forthlevel) {

        $total = ($point/$forthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $fifthlevel) {

        $total = ($point/$fifthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    } elseif ($point <= $sixthlevel) {

        $total = ($point/$sixthlevel) * 100;
        $remaining =  round($total);

        //echo number_format($remaining, 0, '.', ' ');
        return $remaining;
    }


}
  • 写回答

7条回答 默认 最新

  • dongpo8250 2015-08-07 07:16
    关注

    Try this:

    function to_next_level($point) {
    
        /*
        **********************************************************************
        *
        *   This function check how much points user has achievents and how much procent it is until next level
        *
        **********************************************************************
        */
    
        $levelArray = array(3000, 7000, 15000, 28000, 45000, 80000);
        foreach ($levelArray as $level) 
        {
            if ($point <= $level) {
                $total = ($point/$level) * 100;
                $remaining =  round($total);  
    
                //echo number_format($remaining, 0, '.', ' ');
                return $remaining;            
            }
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?