![](/img/trans.png)
[英]how to fill the items in combo box from database based on the selected item of another combo box
[英]how to set selected multiple combo box based on array
我有两组数组,第一个数组包含称为“ all”的所有类别,第二个数组包含称为“ selected”的选定类别,我想将此概念填充到多个组合框中,
$all = [
0 => [
'id'=>1,
'name' => 'news'
],
1 => [
'id'=>2,
'name' => 'tips'
],
2 => [
'id'=>3,
'name' => 'trick'
],
3 => [
'id'=>4,
'name' => 'review'
]
];
$selected = [
0 => [
'id'=>2,
'name' => 'trick'
],
1 => [
'id'=>4,
'name' => 'review'
],
];
我已经尝试在foreach中执行foreach,但是在组合框中显示时我有重复的数据,我希望将“ all”中的所有数据与“ selected”中的选定数据一起显示。
我只是以不同的方式解决了我的问题,首先我在“所有”数组集中添加了默认的键和值对“ sel” => 0,然后循环通过槽“ all”和数组“ sel”以获得相似的值,以及何时它将更改sel键匹配为1,此代码可作进一步说明
public static function compare($sel,$all){
// add sel key with default value = 0
foreach($all as $k=>$v){
$all[$k]['sel'] = 0;
}
foreach($all as $k=>$v){
foreach($sel as $k2=>$v2){
// when match change sel to 1
if($v['id'] == $v2['id']){
$all[$k]['sel'] = 1;
}
}
}
return $all;
}
最后结果 :
$all = [
0 => [
'id'=>1,
'name' => 'news',
'sel' => 0
],
1 => [
'id'=>2,
'name' => 'tips',
'sel' => 0
],
2 => [
'id'=>3,
'name' => 'trick',
'sel' => 1
],
3 => [
'id'=>4,
'name' => 'review',
'sel' => 1
]
];
仅在条件$ all ['sel'] = 1时添加条件,谢谢:D
您可以使用array_uintersect
和自定义的回调函数( compare
)获得两个数组的交集。
function compare($a, $b){
if($a['id'] == $b['id']){
return 0;
}
return 1;
}
$res = array_uintersect($selected, $all,"compare");
print_r($res);
>Array ( [0] => Array ( [id] => 2 [name] => trick ) [1] => Array ( [id] => 4 [name] => review ) )
之后,您只需要遍历最终数组并设置相应的复选框。
如果要按名称进行比较,只需创建另一个回调函数。
function compare2($a, $b){
if($a['name'] == $b['name']){
return 0;
}
return 1;
}
重复是由内部for循环(即使在找到选定元素之后)继续创建select元素引起的。 您可以避免内部循环,并使用php的in_array()函数检查$ all是否在$ selected中,如下所示:
$x = '';
foreach($all as $a){
if(in_array($a, $selected)){
$x .= '<option selected>'.$a['id'].'Selected </option>';
}else{
$x .= '<option>'.$a['id'].'Not selected </option>';
}
}
echo $x;
请注意,in_array将检查元素的所有值,因此,例如ID为2但名称不同的元素将显示为未选中。 您可能需要将两个名称都更改为提示。 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.