我正在尝试生成一个选择列表,所选选项等于包含该列表的组元素。
这是我的代码:
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放在外面,我无法得到row[]
数据,但如果我把它放在里面,它会使值增加一倍或三倍。
关于如何使这项工作的任何想法?
答案 0 :(得分: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>';
答案 1 :(得分: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>';