如何从php中的平板数组中获取折扣值

我正在尝试使用预定义的板作为数组来获取折扣数(值)。


例如,如果总产品数量在 11 到 20 之间,那么我想返回 25 作为折扣值。


这可能很简单,但我不知道该怎么做。因为简单的 foreach 循环可能不起作用。


/**

 * The function returns the discount amount from the slabs

 *

 * @param int $products_count total number of product in cart

 *

 * @return mixed null|int returns discount value if matches else null

 */

public function product_discounts($products_count)

{


    $discount_slabs = [

        '10' => '15',

        '20' => '25',

        '30' => '35',

        '50' => '50',

    ];


    foreach ($discount_slabs as $count => $discount) {


        if ($products_count <= $count) {

            $this->discount = $discount;

        }


    }


    return $this->discount;


}


MMTTMM
浏览 127回答 1
1回答

扬帆大鱼

您只需要在循环中返回折扣,这样当您找到适合产品计数的最小平板时,您就可以停止查看后续值。否则所有值将返回 50%。如果您跳出循环,则用户拥有超过 50 个产品,他们将获得最后一个折扣值,这是最大的一个。像这样的东西:public function product_discounts($products_count){&nbsp; &nbsp; $discount_slabs = [&nbsp; &nbsp; &nbsp; &nbsp; '10' => '15',&nbsp; &nbsp; &nbsp; &nbsp; '20' => '25',&nbsp; &nbsp; &nbsp; &nbsp; '30' => '35',&nbsp; &nbsp; &nbsp; &nbsp; '50' => '50',&nbsp; &nbsp; ];&nbsp; &nbsp; // set the base discount&nbsp; &nbsp; $this->discount = 0;&nbsp; &nbsp; foreach ($discount_slabs as $count => $discount) {&nbsp; &nbsp; &nbsp; &nbsp; if ($products_count <= $count) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if less than this bracket, return the current discount&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $this->discount;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // otherwise, increase the discount level&nbsp; &nbsp; &nbsp; &nbsp; $this->discount = $discount;&nbsp; &nbsp; }&nbsp; &nbsp; return $this->discount = $discount;}
打开App,查看更多内容
随时随地看视频慕课网APP