PHP切换条件语句更好的方式

时间:2017-08-04 15:13:20

标签: php optimization switch-statement conditional-operator

优化此代码的最佳方法是什么?我知道if和else语句会更快,但我想要一些简洁明了的东西。有什么想法吗?

switch ($data['months']) {
case ($data['months'] >= 400):
    $data['months'] = 400;
    break;
case ($data['months'] >= 360):
    $data['months'] = 360;
    break;
case ($data['months'] >= 60):
    $data['months'] = 60;
    break;
case ($data['months'] >= 48):
    $data['months'] = 48;
    break;
case ($data['months'] >= 36):
    $data['months'] = 36;
    break;
case ($data['months'] >= 24):
    $data['months'] = 24;
    break;
case ($data['months'] >= 12):
    $data['months'] = 12;
    break;
case ($data['months'] >= 9):
    $data['months'] = 9;
    break;
case ($data['months'] >= 6):
    $data['months'] = 6;
    break;
case ($data['months'] >= 3):
    $data['months'] = 3;
    break;
case ($data['months'] >= 1):
    $data['months'] = 1;
    break;
default:
    $data['months'] = 12;
}

3 个答案:

答案 0 :(得分:5)

我猜你可以使用foreach和一系列断点。

$breakpoints = array(400, 360, 60, 48, 36, 24, 12, 9, 6, 3, 1);

// Loop through each breakpoints
foreach($breakpoints as $breakpoint){

    // Proceed to next breakpoint
    if($data['months'] < $breakpoint)
        continue;

    // No need to loop through the rest of the array
    $data['months'] = $breakpoint;
    break;

}

// Handle the cases where $data['month'] is less than 1
if($data['months'] < 1)
    $data['months'] = 12;

更新

另一种方法是在循环之前检查$data['months']是否小于1:

if($data['months'] < 1)
    $data['months'] = 12;
else{

    $breakpoints = array(400, 360, 60, 48, 36, 24, 12, 9, 6, 3, 1);

    // Loop through each breakpoints
    foreach($breakpoints as $breakpoint){

        // Proceed to next breakpoint
        if($data['months'] < $breakpoint)
            continue;

        // No need to loop through the rest of the array
        $data['months'] = $breakpoint;
        break;

    }

}

答案 1 :(得分:5)

这样的事情应该可以解决问题。

$breakpoints = [1, 3, 6, 9, 12, 24, 36, 48, 60, 360, 400];

foreach($breakpoints as $breakpoint) {
    if($data['months'] >= $breakpoint) {
        $value = $breakpoint;
    }
}

if(!isset($value)) { $value = 12; }

答案 2 :(得分:0)

这是我最终得到的结果。

git show