【问题标题】:Generate switch cases in php from an array?从数组中生成 php 中的 switch case?
【发布时间】:2012-12-17 22:45:56
【问题描述】:

是否可以使用数组在 php 中生成 switch 的案例?比如:

$x=array(
    0 => 'foo',
    1 => 'bar',
    2 => 'foobar'
);

$y='foobar'

switch($y) {
    foreach($x as $i) {
        case $i:
            print 'Variable $y tripped switch: '.$i.'<br>';
            break;
    }
}

我希望能够从数据库中提取案例值并使用 while() 循环遍历它们。

【问题讨论】:

  • 没有。你想用这个做什么?为什么你认为你需要一个开关/外壳?
  • 无论你想做什么,switch 都会让它变得过于复杂。您想要的东西是不可能的,并且有充分的理由 - 该代码可以简单地编写为foreach($x as $i) { if ($i == $y) { print 'Variable $y tripped switch: '.$i.'&lt;br&gt;'; } }(假设您在该代码示例中混淆了您的$xs 和您的$is)
  • 我并不是真的需要它,它只是我出于猜测而最终修补的东西。

标签: php foreach switch-statement


【解决方案1】:

我相信您正在寻找的是类似的东西

foreach ($x as $i) {
    switch($i){
        case $y:
            print 'Variable $x tripped switch: '.$i.'<br>';
            break;
    }
}

【讨论】:

    【解决方案2】:

    没有。开关是开关,但您可以使用数组键来选择正确的值。基本上在您的数组中,您可以使键和值相同,然后您可以像这样使用 if 函数:

    if ($array[$key]) ....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2011-10-24
      • 1970-01-01
      相关资源
      最近更新 更多