将多个复选框输入保存为数组?

时间:2015-12-16 05:32:45

标签: php arrays foreach

我有一大堆复选框输入,它们都具有相同的名称属性。我想保存它们的值(如果选中则为1,如果不是则为0,因为顺序很重要,我需要以正确的顺序输出它们)作为一个不按预期方式运行的数组。

<input type="checkbox" name="feature[]" id="feature-a"/>
<input type="checkbox" name="feature[]" id="feature-b"/>
<input type="checkbox" name="feature[]" id="feature-c"/>
<input type="checkbox" name="feature[]" id="feature-d"/>

foreach( $_POST['feature'] as $feature ) {

    if( isset( $feature ) && '' !== $feature ) {
        $feature = 1; 
    }
    else {
        $feature = '';
    } 

    $features = array();
    array_push($features, $feature);
}
update_term_meta( $term_id, 'features', $features );

//This always outputs a:1 {i:0;i:1;} for some reason! No matter what I check

我缺少什么?

  1. 我尝试添加feature[]作为名称属性
  2. 我试图帮助&#39;&#39;或&#34;&#34;到$feature
  3. 什么都没有用。我的循环中是否有错误我无法看到?

1 个答案:

答案 0 :(得分:1)

foreach($ _POST [&#39; feature&#39;] as $ feature){

if( isset( $feature ) && $feature !=='' ) {
    $feature = 1; 
}
else {
    $feature = 0;
} 

$features = array();
array_push($features, $feature);

} update_term_meta($ term_id,&#39; features&#39;,$ features);