我设法通过这个函数从数据库中获取结果并将它们放入 -6ren">
gpt4 book ai didi

php - 多选字段 - 多次使用选定的 ="selected"

转载 作者:可可西里 更新时间:2023-11-01 01:05:15 24 4
gpt4 key购买 nike

我有一个这样的多字段:

<select name="excluded_groups[]">
<?php echo $foo->multi_group_select_options($group_ids, $excluded_id); ?>
</select>

我设法通过这个函数从数据库中获取结果并将它们放入 <select> 中,但我无法设法保持选中的值。

第一个参数应该加上selected="selected"对于在提交前标记然后提交的字段,第二个参数阻止显示 group_id(第二个参数按应有的方式工作)。

这里是函数...

/**
* group_options
* Get group names in the dropdown list
*/
public function multi_group_select_options($default = false, $exclude_id = '')
{
global $user;

$exclude_id = (isset($this->config['default_group'])) ? $this->config['default_group'] : 5;

$sql_where = ($user->data['user_type'] == USER_FOUNDER) ? '' : 'WHERE group_founder_manage = 0';
$sql_where_and = (!empty($sql_where)) ? ", AND group_id <> $exclude_id" : "WHERE group_id <> $exclude_id";
$sql = 'SELECT group_id, group_name, group_type
FROM ' . GROUPS_TABLE . "
$sql_where
$sql_where_and
ORDER BY group_name";
$result = mysql_query($sql);

$s_group_options = '';
while ($row = mysql_fetch_assoc($result))
{
/*if (is_array($default))
{
break;
$group_id = '';
foreach ($default as $key => $group_id)
{
$group_id = $group_id;
}
}

print_r($default);*/

$selected = ($row['group_id'] == $group_id) ? ' selected="selected"' : '';
$s_group_name = ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
$s_group_options .= '<option' . (($row['group_type'] == GROUP_SPECIAL) ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '"' . $selected . '>' . $s_group_name . '</option>';
}
$db->sql_freeresult($result);

return $s_group_options;
}

我作为第一个参数放置的数组是完全有效的。它只是一个包含键和值的普通数组,其中值是组 ID。

尝试在 while 内使用 foreach - 没有用,在 while 循环外也是如此。

$default 数组如下所示:

Array
(
[0] => 1
[1] => 7
[2] => 2
[3] => 3
)

最佳答案

您的代码有几个问题。

首先,函数接受$exclude_id作为参数,但忽略参数并将其分配给:

$exclude_id = (isset($this->config['default_group'])) ? $this->config['default_group'] : 5;

其次,你说这应该是多选,但是你的<SELECT>标签没有 MULTIPLE属性。

第三,你在比较$row['group_id']$group_id .这只允许一个默认值,而不是多个默认值,你甚至没有设置变量(设置它的代码被注释掉了,但它只会将它设置为 $default 数组的最后一个元素。DCoder 的评论似乎喜欢这个的正确解决方案。

关于php - 多选字段 - 多次使用选定的 ="selected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12489034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com