簡體   English   中英

PHP中的For Loop Inside Switch語句

[英]For Loop Inside Switch Statement in PHP

我將某些范圍保存在數組中,價格在索引[3]處,折扣類型在索引[4](%,固定)。 在這些范圍內購買的任何人都應該獲得可用的折扣。 我當前的問題是數組的范圍可以是任意數,例如,在$a變量中,有4 nested array ,但是在某些情況下,我將制作6 nested array8 nested array ,依此類推向前。

因此,我在switch語句中運行了for循環,並且遇到了一個Parse error: syntax error, unexpected 'for' (T_FOR), expecting case (T_CASE) or default (T_DEFAULT) or '}'

這是我的代碼:-

<?php

$a = array(array('0', '10', '200', '0'), array('11', '20', '20', '1'), array('20', '50', '25', '1'), array('50', '100', '5000', '0'));

$quantity = 25;

$count = count($a);


switch($quantity) {
    for($i=0;$<=$count-1;$i++) {
        case ($quantity > $a[$i][0] && $quantity < $a[$i][1]) :
            echo "Discount Available for Quantity > ".$a[$i][0]." and < ".$a[$i][1];
            break;
    }
    default:
        echo 'No Discount';
        break;
}

?>

我應該如何為上述情況設計算法。

注意 :數組類型:-

$variable = array ("lowest_quantity_range", "highest_quantity_range", "discount_value", "discount_type");

折扣類型將為1表示%0表示fixed金額)

您不能在switch語句內使用for循環。 您需要將for循環放在switch語句之外:

<?php

$a = array(array('0', '10', '200', '0'), array('11', '20', '20', '1'), array('20', '50', '25', '1'), array('50', '100', '5000', '0'));

$quantity = 25;

$count = count($a);

foreach($a as $item) {
switch($quantity) {

        case ($quantity >$item[0] && $quantity < $item[1]) :
            echo "Discount Available for Quantity > ".$item[0]." and < ".$item[1];
            break;
       default:
        echo 'No Discount';
        break;
}
    }
?>

似乎您根本不​​應該在這里使用任何開關...

$a = array(
    array('0', '10', '200', '0'),
    array('11', '20', '20', '1'),
    array('20', '50', '25', '1'),
    array('50', '100', '5000', '0')
);

$quantity = 25;
$found = false;

foreach ($a as $item)
{
    if ($quantity >$item[0] && $quantity < $item[1])
    {
        echo "Discount Available for Quantity > ".$item[0]." and < ".$item[1];
        print_r($item);
        $found = true;
    }
}

if (!$found)
{
    echo "No Discounts";
}

實施例for在-loop switch語句:

if( isset( $_POST[ "action" ] ) ) { 
    $action = $_POST[ "action" ];
    switch ( $action ) {
        case "add" : addItem(); break;
        case "del" : delItem(); break;
        case "undo" : for(
                            $i = 0; 
                            $i <= 10; 
                            $i ++ ) { 
                        switch ( $_SESSION[ "id" ] ) {
                            case $i : undoAction( $i ); break; 
                        }
                     }
                     $_SESSION = array();
                     break;
    }
}

我記得我曾經做過一個腳本,所以在這里抓住了它。 確保您的for -loop在case定義之后啟動。 在這個例子中是"undo": ...通常for -loops被包裝在一個function或方法,使之更加干凈。 您不能在switch語句中為新case就地啟動for -loop。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM