0

我是 php 开发的新手,我正在努力编写一个代码来检查条件以在下拉列表中设置选定的值

 while ($row = $result_departments->fetch_assoc()) {
        $dept_info = array(
            'name'  => $row['dpt_name'],
             'id'    => $row['dpt_id']
        );
        $departments.= '<option value="'.$dept_info['name'].'" name="'.$dept_info['name'].'">'.$dept_info['name'].'</option>';

      }
return $departments;

在填充 $departments 时我想添加条件if $dept_info['name']=="XYZ" selected=="selected"怎么做?我无法编写正确的语法。

4

3 回答 3

1

你可以用一个简单的 if 来做到这一点:

$departments.= '<option value="'.$dept_info['name'].'" name="'.$dept_info['name'].'"';

if ($dept_info['name']=="XYZ")
    $department.= ' selected="selected"';

$department .='>'.$dept_info['name'].'</option>';

第二种方法是三元运算符:

$departments.= '<option value="'.$dept_info['name'].'" name="'.$dept_info['name'].'"';   
$department.= ($dept_info['name']=="XYZ"?' selected="selected"':null);
$department .='>'.$dept_info['name'].'</option>';
于 2013-10-22T20:53:12.770 回答
0

一个简单的 if/else 应该可以解决问题。

while ($row = $result_departments->fetch_assoc()) {
    $dept_info = array(
        'name'  => $row['dpt_name'],
        'id'    => $row['dpt_id']
    );
    if(dept_info['name'] == "XYZ") {
        $departments.= '<option value="'.$dept_info['name'].'" name="'.$dept_info['name'].'" selected="selected">'.$dept_info['name'].'</option>';
    } else {
        $departments.= '<option value="'.$dept_info['name'].'" name="'.$dept_info['name'].'">'.$dept_info['name'].'</option>';
    }
}
return $departments;
于 2013-10-22T20:52:14.317 回答
0

尝试这个:

 while ($row = $result_departments->fetch_assoc()) {
    $dept_info = array(
        'name'  => $row['dpt_name'],
         'id'    => $row['dpt_id']
    );
    $select_it = ($dept_info['name']=="XYZ") ? 'selected' : '';

    $departments.= '<option $select_it value="'.$dept_info['name'].'" name="'.$dept_info['name'].'">'.$dept_info['name'].'</option>';

  }
return $departments;
于 2013-10-22T20:52:05.867 回答