0

我正在尝试生成一个选择列表,其中所选选项等于包含该列表的组元素。

这是我的代码:

echo '<select title="Show Article in Group" id="edt-select-art">';

$result = mysqli_query($con,"SELECT * FROM groups");

$groups = array();
while($row = mysqli_fetch_array($result)) {
    array_push($groups, $row['0']);

    foreach($groups as $group) 
        { 
            if($gID == $group)
                {
                    echo '<option agid="'.$row['0'].'" selected>'.$row['2'].'</option>';
                }
            else
                {
                    echo '<option agid="'.$row['0'].'">'.$row['2'].'</option>';
                }
        }       

}
echo '</select>';

如果我将 foreach 放在 while 外面,我无法获取row[]数据,但如果我把它放在里面,它的值会增加一倍或三倍。关于如何使这项工作的任何想法?

4

2 回答 2

1

与其推入行 [0],不如将行推入组中,然后迭代组数组,如下所示:

echo '<select title="Show Article in Group" id="edt-select-art">';

$result = mysqli_query($con,"SELECT * FROM groups");

$groups = array();

while($row = mysqli_fetch_array($result)) {
    array_push($groups, $row);


}
 foreach($groups as $group) 
        { 
            if($gID == $group[0])
                {
                    echo '<option agid="'.$group['0'].'" selected>'.$group['2'].'</option>';
                }
            else
                {
                    echo '<option agid="'.$group['0'].'">'.$group['2'].'</option>';
                }
        }       

echo '</select>';
于 2013-06-28T16:59:09.977 回答
0

你不需要$groups数组。

echo '<select title="Show Article in Group" id="edt-select-art">';
$result = mysqli_query($con,"SELECT * FROM groups");
while($row = mysqli_fetch_array($result)) {
    echo '<option agid="'.$row['0'].'" '.($row['0'] == $gId ? 'selected' : '').'>'.$row['2'].'</option>';   
}
echo '</select>';
于 2013-06-28T17:02:13.763 回答