如何在 php 中根据我的条件使用开关大小写


How to use switch case according my condition in php

 if($this->input->get('i1')!='' && $this->input->get('i2')=='' && $this->input->get('i3')=='' && $this->input->get('i4')=='')
            {
                echo 'i1';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')=='' && $this->input->get('i4')=='')
            {
                echo 'i1  i2 ';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')!='' && $this->input->get('i4')=='')
            {
                echo 'i1 i2 i3';
            }else
            if($this->input->get('i1')!='' && $this->input->get('i2')!='' && $this->input->get('i3')!='' && $this->input->get('i4')!='')
            {
                echo 'i1 i2 i3 i4';
            }

如何在开关情况下使用此条件...任何人都可以帮助我。

一种可能的解决方案是像位掩码一样生成。

定义只是为了使代码更具可读性。

// create costants to make the code more readable           
define('I1', '1000'); 
define('I1_I2', '1100'); 
define('I1_I2_I3', '1110'); 
define('I1_I2_I3_I4', '1111'); 
// controll you input and cast in iteger
// true  -> 1
// false -> 0
for ($i = 1; $i < 5; $i++) {
    $var  = 'i' . $i;
    $$var =  $this->input->get($var)
    $$var = (int) !empty($$var);
}
// generate a mask
// eg : 1000
$mask = $i1.$i2.$i3.$i4;
switch ($mask) {
    case I1:
        echo 'i1';
        break;
    case I1_I2:
        echo 'i1 i2';
        break;
    case I1_I2_I3:
        echo 'i1 i2 i3';
        break;
    case I1_I2_I3_I4:
        echo 'i1 i2 i3';
        break;
}
我知道

这不是开关情况,但是既然您澄清了您要简化,那么这会满足您的需求吗?

for($x=1;$x<=4;$x++){
    if(!empty($this->input->get('i'.$x)) echo "i$x ";
}

不是真正的答案,但下面的看起来也不那么冗长。

if($this->input->get('i1')!='')
{
    echo 'i1 ';
    if($this->input->get('i2')!='')
    {
        echo 'i2 ';
        if($this->input->get('i3')!='')
        {
            echo 'i3 ';
            if($this->input->get('i4')!='')
            {
                echo 'i4 ';
            } 
        } 
    } 
}

我认为开关大小写对这里的简化没有多大帮助。相反,我建议一个更动态的解决方案。像这样:

$inputs = $this->input->only('i1', 'i2', 'i3', 'i4');
$notEmptyInputs = array_filter($inputs);
echo implode(' ', array_keys($notEmptyInputs));

如果您不希望输出像 i1 i4 这样的输出,而只想要在未设置 2 和 3 的情况下i1输出,请使用以下命令:

$inputs = $this->input->only('i1', 'i2', 'i3', 'i4');
$notEmptyInputs = [];
foreach($inputs as $key => $value){
    if(empty($value)){
        break;
    }
    $notEmptyInputs[] = $key;
}
echo implode(' ', $notEmptyInputs);