如何将关联数组的值传递给复选框

时间:2018-02-08 04:25:06

标签: php

以下片段通过比较两个数组生成3个具有正确状态的复选框,但是outpt dosent为标签呈现任何值,如

enter image description here

但我需要为

等输入显示$items的值

enter image description here

你可以告诉我如何修改代码来实现这个目标吗?

<?php
$items = ['2' => 'Full', '4' => 'No', '3' => 'Semi'];
$selected = [2, 3];

$keys = array_keys($items);
foreach($keys as $key ){
    if (in_array($key, $selected)) {
         echo '<input id="checkBox" value="'.$key.'" type="checkbox" checked>';
    }
    else{
         echo '<input id="checkBox" value="'.$key.'" type="checkbox">';
    }
}

?>

2 个答案:

答案 0 :(得分:1)

试试这个:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
  <div class="row">
    <div class="col-xs-3">
      <div class="wrapper">
        <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="" />
      </div>
    </div>
    <div class="wrapper">
      <div class="col-xs-3">
        <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="" />
      </div>
    </div>
    <div class="wrapper">
      <div class="col-xs-3">
        <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="" />
      </div>
    </div>
    <div class="wrapper">
      <div class="col-xs-3">
        <img src="http://via.placeholder.com/350x150" class="img-responsive" alt="" />
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:1)

以这种方式尝试:

foreach($items as $key => $value ){
 if (in_array($key, $selected)) {
     echo '<input id="checkBox" value="'.$key.'"  type="checkbox" checked>'.$value.'<br>';
   }
    else{
        echo '<input id="checkBox" value="'.$key.'"   type="checkbox">'.$value.'<br>';
    }
  }