doulin9679 2016-10-13 03:24
浏览 11
已采纳

如何简化此PHP脚本?

I'd like to add "selected" attribute to a combo box. This is my PHP:

if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }

if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }

if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }

if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }

I may have over hundreds of IF's.

I've tried this one, but It seems not working:

for($a=1; $a<=4; $a++){
    if($results['status'] == $a)
    { $ok = "selected"; }
    else
    { $ok = ""; }

}

I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way

Edit (My combo box):

<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
  • 写回答

5条回答 默认 最新

  • douyong7199 2016-10-13 03:39
    关注

    Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!

    // initialize all 4 to blank
    for($a=1; $a<=4; $a++){
        ${"ok" . $a} = "";
    }
    // set the one that is selected 
    ${"ok" . $results['status']} = "selected";
    

    This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?