PHP:在php循环中选择一个选项

时间:2014-03-12 10:31:56

标签: php

我有以下内容从数据库中生成选项

foreach($categories as $rowcat)
{echo '<option value="'.$rowcat->catname.'">'.$rowcat->catname.'</option>';
}

我需要在加载时选择一个选项,所以我将如何插入

selected="Office"

2 个答案:

答案 0 :(得分:1)

foreach($categories as $rowcat){                   

echo '<option value="'.$rowcat->catname.'" '.($rowcat->catname=='Office') ? 'selected="selected"' : ''.'>'.$rowcat->catname.'</option>';                
}

答案 1 :(得分:1)

$opt = "Office";
foreach($categories as $rowcat){                   
    if( $row->catname == $opt ) {
    echo '<option value="'.$row->catname.'" selected="selected">'.$rowcat->catname.'</option>';                
   }
   else {
    echo '<option value="'.$row->catname.'">'.$rowcat->catname.'</option>';
   }
}