价格不同,取决于星期几PHP

时间:2018-10-14 12:05:59

标签: php

我正在学习PHP,我希望根据一周中的某一天为我的产品显示不同的价格。例如,周一的价格应降低50%,周三的价格应提高10%,依此类推。 我当时在考虑使用带有switch语句的函数,但是无法使其正常工作。希望有人能给我一些提示!

    function day_of_week($day) {
    $day = "Monday";

    switch ($day) {
        case "Monday":
            $key['price'] / 2;
            break;
        case "Wednesday":
            $key['price'] * 1.1;
            break;
        case "Friday":
            if($key['price'] >= 200) {
                $key['price'] - 20;
            }   
    }

}
Today's price:
<?php echo day_of_week($day); ?>

2 个答案:

答案 0 :(得分:1)

正如评论中提到的那样,有很多问题,例如$ day再次重新初始化,而$ key不在函数范围内,并且不返回任何内容等...

以下是工作代码:

<?php
$day = date('l');
$key['price'] = 2000;
function day_of_week($day , $price) {

    switch ($day) {
        case "Monday":
            return $price / 2;
        case "Wednesday":
            return $price * 1.1;
        case "Friday":
            if($price >= 200) {
                return $price - 20;
            }
    }
    return $price;
}
echo "Price for ".$day.": ".day_of_week($day, $key['price']);

 ?>

另一种可能的方式!

<?php
/**
 * Created by PhpStorm.
 * User: Ussaid Iqbal
 * Date: 10/14/18
 * Time: 4:09 PM
 */
$day = "Wednesday";
$key["price"] = 2000;

function day_of_week($day) {
    global $key;
    switch ($day) {
        case "Monday":
            return $key["price"] / 2;
        case "Wednesday":
            return $key["price"] * 1.1;
        case "Friday":
            if($key["price"] >= 200) {
                return $key["price"] - 20;
            }
    }
    return $key["price"];
}
echo "Today's price: ".day_of_week($day);

 ?>

答案 1 :(得分:0)

您可以创建一个anonymous object作为控制器来执行此操作。这就需要创建anonymous functions并使用call_user_func_array()来执行闭包。

$priceChart = (object)
[
    'monday' => function($price) {
        return (int) $price / 2;
    },
    'wednesday' => function($price) {
        return (int) $price * 1.1;
    },
    'friday' => function($price) {
        return (int) $price > 200 ? (int) $price - 20 : (int) $price;
    }
];

$price = 20.00; // Can be of type string
$currentDay = 'WednEsdAy'; // Capitals do not matter or use date('l');
$newPrice = isset($priceChart->{strtolower($currentDay)}) ? call_user_func_array($priceChart->{strtolower($currentDay)}, [$price]) : $price;

您可以在{3v4l} see a working example结束。