PHP:复选框数组中的checked属性

时间:2018-05-26 17:05:10

标签: php forms checkbox

我有一个像这样的数组

$current_asset = [
    ['name'=>'Land,'id'=>1],
    ['name'=>'Building ,'id'=>2],
    ['name'=>'Machinery','id'=>3],
];

<?php 
 foreach($current_asset as $key=>$value){ ?>
 <input type="checkbox" name="current_asset[]" value="<?php echo $value['id'] ?>">

 <?php } ?>

我的问题如果在填充了POST数据的表单

时检查了其中一个值,我该如何添加checked属性?

我在表单提交

上获得了这样的复选框数组

以下是表单提交的当前复选框(即current_asset

的值
Array(
    0=>1
    1=>1
   )

2 个答案:

答案 0 :(得分:1)

您需要在打印之前进行某种检查

$html=‘’;
foreach($current_asset as $asset) {
 if($asset[‘hasBeenCheckedBefore’]) {
  $checked = ‘checked’;
 } else {
  $checked = ‘’;
 }
 $html .= “$asset[‘name’] <input type=‘checkbox’ name=‘current_asset[]’ value=‘$asset[“id”]’ $checked />”;
}

答案 1 :(得分:0)

以下是一种方法的示例。我已将您的数据结构更改为更易于使用。我最初很困惑,因为你没有提到任何存储数据的方法。所以这只适用于单页视图。

<?php

// initialize data

/**
 * Data structure can make the job easy or hard...
 *
 * This is doable with array_search() and array_column(),
 * but your indexes might get all wonky.
 */
$current_asset = [
    ['name'=>'Land','id'=>1],
    ['name'=>'Building' ,'id'=>2],
    ['name'=>'Machinery','id'=>3],
];

/**
 * Could use the key as the ID.  Note that it is being
 * assigned as a string to make it associative.
 */
$current_asset = [
    '1'=>'Land',
    '2'=>'Building',
    '3'=>'Machinery',
];

/**
 * If you have more information, you could include it
 * as an array.  I am using this setup.
 */
$current_asset = [
    '1'=> ['name' => 'Land',      'checked'=>false],
    '2'=> ['name' => 'Building',  'checked'=>false],
    '3'=> ['name' => 'Machinery', 'checked'=>false],
];


// test for post submission, set checked as appropriate
if(array_key_exists('current_asset', $_POST)) {
  foreach($_POST['current_asset'] as $key => $value) {
    if(array_key_exists($key,$current_asset)) {
      $current_asset[$key]['checked'] = true;
    }
  }
}



// begin HTML output
?>
<html>
  <head>
    <title></title>
  </head>
  <body>

    <!-- content .... -->

    <form method="post">
    <?php foreach($current_asset as $key=>$value): ?>
      <?php $checked = $value['checked'] ? ' checked' : ''; ?>
      <label>
        <input type="checkbox" name="current_asset[<?= $key ?>]" value="<?= $key ?>"<?= $checked ?>>
        <?= htmlentities($value['name']) ?>
      </label>
    <?php endforeach; ?>
    </form>

  <body>
</html>