foreach表单内的复选框数组。将每个复选框与另一个变量相关联

时间:2013-11-26 08:44:13

标签: php checkbox foreach key-value

对于以下示例,当检查所有复选框时,一切都按预期工作。当检查一个或多个(但不是全部)时会出现问题。

<form action="someaction" method="post">
 <?php foreach ($fields as $field) { ?>
  <input type="checkbox" name="checkpid[]" value="<?php echo $field['pid']; ?>">
  <input type="hidden" name="checkprice[]" value="<?php echo $field['price']; ?>">
  <input type="submit" name="submit" value="Submit">
 <?php } ?>
</form>

<?php if (isset($_POST['checkpid'])) { ?>
 <?php
  $checkpid = $_POST['checkpid'];
  $checkprice = $_POST['checkprice'];
 ?>

  <?php foreach ($checkpid as $key => $checkpid) { ?>
   <?php
    $eachpid[] = $checkpid.",".$checkprice[$key];    
   ?>
  <?php } ?>

   <?php print_r($eachpid), ?> // the $checkpid is always as expected, but the $checkprice does not match its row.
<?php } ?>

凭借我的小知识,我怀疑在$ key的声明中出现了问题,但我感到不知所措。

1 个答案:

答案 0 :(得分:0)

这就是我所能提出的建议。

而不是添加两个输入如何在以|分隔的复选框输入的值中添加两个数据。然后在提交时只是爆炸值并接收数组1的id和1的价格。

<?php 
  if (isset($_POST['checkp'])) { 

    $checkp = $_POST['checkp'];
    foreach ($checkp as $check) { 
      $c = explode("|", $check);
      $eachpid[] = $c[0].",".$c[1];    
    }

    print_r($eachpid);
  } 
?>

<form action="" method="post">
 <?php foreach ($fields as $field) { ?>
  <input type="checkbox" name="checkp[]" value="<?php echo $field['pid']; ?>|<?php echo $field['price']; ?>">
<?php } ?>
<input type="submit" name="submit" value="Submit">
</form>