多If压缩-PHP
所以我有这个密码。。。(对不起) (我的问题需要更多的“细节”,因为代码太长了) 基本上,它接受用户的拥抱计数,每隔一段时间它会给他们一个新的报价作为奖励,但间隔是不规则的多If压缩-PHP,php,arrays,if-statement,Php,Arrays,If Statement,所以我有这个密码。。。(对不起) (我的问题需要更多的“细节”,因为代码太长了) 基本上,它接受用户的拥抱计数,每隔一段时间它会给他们一个新的报价作为奖励,但间隔是不规则的 if ($hugs > 0) { $quote = $quotes[0]; } if ($hugs > 5) { $quote = $quotes[1]; } if ($hugs > 10) { $quote = $quotes[2]; } if ($hugs > 20) {
if ($hugs > 0) {
$quote = $quotes[0];
}
if ($hugs > 5) {
$quote = $quotes[1];
}
if ($hugs > 10) {
$quote = $quotes[2];
}
if ($hugs > 20) {
$quote = $quotes[3];
}
if ($hugs > 50) {
$quote = $quotes[4];
}
if ($hugs > 100) {
$quote = $quotes[5];
}
if ($hugs > 150) {
$quote = $quotes[6];
}
if ($hugs > 200) {
$quote = $quotes[7];
}
if ($hugs > 250) {
$quote = $quotes[8];
}
if ($hugs > 500) {
$quote = $quotes[9];
}
if ($hugs > 750) {
$quote = $quotes[10];
}
if ($hugs > 1000) {
$quote = $quotes[11];
}
if ($hugs > 1500) {
$quote = $quotes[12];
}
由于拥抱次数之间的间隔是不规则的,有没有办法将其压缩
TIA。以下是一种组织方式:
function getQuote($hugs) {
$hugQuotes = array(
array(1500, $quotes[12]),
array(1000, $quotes[11]),
...
);
foreach($hugQuotes as $v) {
$c = $v[0];
$quote = $v[1];
if ($hugs > $c) return $quote;
}
return $quote;
}
像这样的东西怎么样:
$steps = array(0, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 1500);
foreach ($steps as $index => $step) {
if ($hugs > $step) {
$quote = $quotes[$index];
}
}
这使用
$steps
数组将$quotes
数组中的索引映射到下一步。您当然可以压缩它!一种方法是构建关联数组(键值对),如下例所示
/**
* Returns a quote based on the number of hugs
*
* @param int $hugs
* @param array $quotes
*
* @return string|null
*/
function getQuoteFromHugs($hugs, $quotes) {
$hugs_quotes = array(
1500 => $quotes[12],
1000 => $quotes[11],
750 => $quotes[10],
500 => $quotes[9],
250 => $quotes[8],
200 => $quotes[7],
150 => $quotes[6],
100 => $quotes[5],
50 => $quotes[4],
20 => $quotes[3],
10 => $quotes[2],
5 => $quotes[1],
0 => $quotes[0],
);
foreach($hugs_quotes as $hug_minimum => $quote) {
if($hugs > $hug_minimum) {
return $quote;
}
}
return null;
}
// Usage
$quote = getQuoteFromHugs($hugs, $quotes);
这将按顺序遍历每个键值对,并查看$hugs参数是否大于键。如果是这样,它将返回与该键关联的值。我个人会使用switch语句和cases。只要把if的顺序从高到低颠倒过来;您的hugQuotes数组不具有关联性,因此无法获得预期的结果!如果您交换比较,您可以在其中添加一个
中断
,使其更有效一点您的意思是foreach($steps as…
)?编辑为在函数调用中包含$quotes作为变量。工作出色,谢谢!我之所以没有这样做,是因为我担心它可能不会按照我们想要的顺序迭代。