简体   繁体   English

根据数组值设置复选框选中状态

[英]set checkbox checked state based on array values

Let's say I have a bunch of checkbox inputs initially on a page like this: 假设我最初在这样的页面上有很多复选框输入:

<input type="checkbox" name="vehicle" value="Car" /> Car<br />
<input type="checkbox" name="vehicle" value="Bike" /> Bike<br />
<input type="checkbox" name="vehicle" value="Motorcycle" /> Motorcycle<br />
<input type="checkbox" name="vehicle" value="Bus" /> Bus<br />
<input type="checkbox" name="vehicle" value="Car" /> Train<br />

Now let's say that I have an array like this: 现在让我们说我有一个像这样的数组:

$my_array = array(
    'first' => 'Bike', 
    'second' => 'Car', 
    'third' => 'Train'
);

As you can see, my array contains values which correspond to the value of my checkboxes. 如您所见,我的数组包含的值与我的复选框的值相对应。

Now, how do I set the state of each checkbox input based on the value of my array and make the checkbox stay checked even on page refresh using php? 现在,如何基于数组的值设置每个复选框输入的状态,并确保即使在使用php刷新页面时,复选框也保持选中状态? In other words, I want to display all the checkboxes on my page but only those whose values match the value in my array should be checked on the page. 换句话说,我想在页面上显示所有复选框,但是只有那些值与数组中的值匹配的复选框才应在页面上选中。 Is this possible with just straight PHP or do I need javascript for this? 是否可以直接使用PHP还是为此需要JavaScript?

Any idea please? 有什么想法吗? I have tried almost everything with no success 我尝试了几乎所有方法,但都没有成功

Sure, you can do this with PHP... 当然,您可以使用PHP执行此操作...

<input type="checkbox" name="vehicle" value="Car" <?php if(in_array('Car', $my_array)) echo( 'selected = "selected"'); ?>/> Car<br />

Rinse and repeat for all of your checkboxes. 冲洗并重复所有复选框。

However, it would be smarter if you also kept an array containing all possible options. 但是,如果您还保留一个包含所有可能选项的数组,则会更聪明。 Then you could just iterate over that array and check each entry in that array to see if it also exists in your 'selected' array. 然后,您可以遍历该数组并检查该数组中的每个条目,以查看它是否也存在于“选定”数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM