PHP - 产品计数器(奇数和偶数)

时间:2014-01-29 15:16:37

标签: php count

我需要能够根据客户购物篮中的卡数确定我的在线商店需要多少个信封。所以:

1 card = 1 Single Envelope
2 cards = 1 Double Envelope

我有以下检查:

$cards = 2
if ($number % 2 == 0) {
  // double envelope
}
else {
  // single envelope
}

如果他们订购了1张或2张卡,哪种工作正常,但如果他们订购的更多,我需要使用相同的逻辑,但要加上信封。所以如果他们有:

3 cards = 1 x Single & 1 x Double
4 cards = 2 x Double
15 cards = 1 x Single & 7 x Double
20 cards = 10 x Double
and so on...

我该怎么做?

2 个答案:

答案 0 :(得分:1)

$numDoubles = round($cards / 2, 0, PHP_ROUND_HALF_DOWN);
if($cards % 2 == 1) {
    $numSingles = 1;
} else {
    $numSingles = 0;
}

根据评论编辑包括回合。

答案 1 :(得分:0)

$cards = 4;
$doubles = floor($cards / 2);
$singles = $cards % 2;