【问题标题】:if statement within echo within foreachif 语句在 foreach 中的 echo 中
【发布时间】:2015-04-08 18:52:55
【问题描述】:

我正在尝试基于数组在<option> 上设置selected,我已经接近了,但还没有完全到达那里......

$departments = array("Finance", "IT", "Retail",);

foreach($departments as $list){
    echo '<option';
    if($found['dept'] == '$list'){ // if I set this manually it works, but not now
        echo ' selected';
    }
    echo ' >' . $list . ' </option>'; // this works fine to show me the list
}

如果我像下面这样手动设置$found[dept],回显“已选择”效果很好,但我不想为每个选项编写此行的版本。

if($found['dept'] == 'Finance'){ echo 'selected';} > ' .$list . '</option>

【问题讨论】:

  • @Rizier123 虽然the answer to that question 可能会导致解决这个问题,但它远不是重复的。
  • @GolezTrol 但这是 OP 遇到/遇到的问题
  • @Rizier123 因此,您可以在评论中链接到该问题,或提供引用该问题的答案。但这不是同一个问题,因此不应将其作为重复项关闭。明智地使用你的 Dupe Hammer。 :)

标签: php arrays if-statement foreach


【解决方案1】:

你的变量是单引号,这使它成为一个字符串。如果您从输出中分解出您的逻辑,则更容易看到此类错误。

$departments = array("Finance", "IT", "Retail",);

foreach($departments as $list){
    $selected  = ($found['dept'] == $list) ? ' selected' : '';
    echo "<option$selected>$list</option>"; 
}

【讨论】:

  • 答案原来是我的错误是 $list 周围的单引号,但您的回答对我的帮助不仅仅是回答。干杯!
猜你喜欢
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
  • 2012-11-29
  • 2016-06-28
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多