【问题标题】:PHP foreach loop returning the matching itemPHP foreach 循环返回匹配项
【发布时间】:2021-01-11 06:42:54
【问题描述】:

我想在 foreach 循环中返回匹配项的值。我已经尝试过使用打击代码,但它没有正确返回。如果与最后一项匹配,则不会返回正确的值。

//$bonuses = count => amount
Array
(
    [15] => 25
    [30] => 50
    [46] => 100
)

// getting keys to compare the count
$counts = array_keys($bonuses);

foreach ($bonuses as $count => $bonus) {
    if ($total_number_of_products <= next($counts)) {
    $tti = 'Items: '. $total_number_of_products. ' Bonus: '. $bonus. '<BR/>';
    }
}

如果小于或等于,循环应该返回项目。如果计数为46 或更高(在这种情况下),则输出应为100。现在它正在返回50

【问题讨论】:

  • 那么10个产品的奖金是0? 40 就是 50?
  • 没错。这是一个固定的奖金。只有当计数达到数字时,用户才会得到。没有中间人。

标签: php arrays loops foreach


【解决方案1】:

你在正确的轨道上,但你只需要输出之前的奖励值,直到你到达下一个键。这是一种方法:

function get_bonus($total_number_of_products) {
    $bonuses = array(15 => 25, 30 => 50, 46 => 100);
    $bonus = 0;
    foreach ($bonuses as $num_products => $next_bonus) {
        if ($total_number_of_products < $num_products) break;
        $bonus = $next_bonus;
    }
    return $bonus;
}

示例用法:

foreach ([10, 20, 30, 45, 46, 50] as $products) {
    echo 'Items: '. $products. ' Bonus: '. get_bonus($products). '<BR/>' . "\n";
}

输出:

Items: 10 Bonus: 0<BR/>
Items: 20 Bonus: 25<BR/>
Items: 30 Bonus: 50<BR/>
Items: 45 Bonus: 50<BR/>
Items: 46 Bonus: 100<BR/>
Items: 50 Bonus: 100<BR/>

Demo on 3v4l.org

请注意,您可以通过在 $bonuses 中添加 0 =&gt; 0 条目来进行小幅简化,然后您可以删除 $bonus = 0 行,即

function get_bonus($total_number_of_products) {
    $bonuses = array(0 => 0, 15 => 25, 30 => 50, 46 => 100);
    foreach ($bonuses as $num_products => $next_bonus) {
        if ($total_number_of_products < $num_products) break;
        $bonus = $next_bonus;
    }
    return $bonus;
}

【讨论】:

  • @CodeLover 不用担心 - 我很高兴能提供帮助。
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2012-07-19
  • 2017-03-10
相关资源
最近更新 更多