gpt4 book ai didi

php - 用数组重写 PHP 函数

转载 作者:行者123 更新时间:2023-12-04 14:33:26 24 4
gpt4 key购买 nike

有什么方法可以用数组而不是所有这些 if 语句来重写这个函数吗?我可以将一些 for 循环与数组一起使用吗?那会是什么样子?有更简单代码的建议吗?

这是我的 php 函数:

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;
}


}

最佳答案

试试这个:

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;
}
}

}

关于php - 用数组重写 PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com