php 如何使用html表单提交多个数组复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11820608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:11:36  来源:igfitidea点击:

How to submit multiple array checkbox with html forms

phphtmlforms

提问by mk_89

I am trying to submit multiple arrays with a checkbox form but I am only able to submit one array at the moment, here is what I have so far

我正在尝试使用复选框表单提交多个数组,但目前我只能提交一个数组,这是我目前所拥有的

In this example I am submitting an array of numbers with the delete[]array, this array gets processed properly, I also want to submit the array condition[]this does not get processed properly, what is the best way to solve this issue?

在这个例子中,我用数组提交了一个数字delete[]数组,这个数组得到了正确处理,我也想提交condition[]这个没有得到正确处理的数组,解决这个问题的最佳方法是什么?

php code

代码

$catalog = $database->getInventory();

if($catalog){   
   $numRows = sizeof($catalog);//count
   echo "<b>Book Count:</b> ".$numRows."<br>";

   echo "<form method='post' action='inventory.php'>";
   echo "<table id='example' class='tablesorter' border='0' cellpadding='0' cellspacing='1'>";
   echo "
      <thead>
         <tr>
           <th>ISBN</th>        
           <th>Title&nbsp;&nbsp;&nbsp;</th>
           <th>Rank&nbsp;&nbsp;</th>
           <th>Condition&nbsp;&nbsp;</th>   
           <th><input type='checkbox' name='delete' value='all' /></th>
         </tr>
      </thead>\n";


   foreach($catalog as $elem){
      echo "
         <tr>
            <td>".$elem["isbn"]."</td>
            <td>".$elem["title"]."</td>
            <td>".$elem["rank"]."</td>
            <td>".$elem["condition"]."</td>
            <td> 
               <input type='checkbox' name='add[]' 
                  value='".$elem['isbn']."_".$elem['condition']."_"."' />
            </td>
         </tr>";    
   }

   echo "</table>";
   echo "</form>";
}

example html markup

示例 html 标记

<form method='post' action='inventory.php'>
   <table>
      <tr>
         <td>
            <input type='hidden' name='addInventoryBook' value='1'>
            <input type='submit' value='Add' />
         </td>
      </tr>

      <tr>
         <td>
            <input type='checkbox' name='add[]' value='100001_used' />
         </td>
      </tr>

      <tr>
         <td>
            <input type='checkbox' name='add[]' value='100001_new' />
         </td>
      </tr>

      <tr>
         <td>
            <input type='checkbox' name='add[]' value='100003_new' />
         </td>
      </tr>

   </table>
</form>

php function

php函数

function Inventory(){   
   if(isset($_POST['addInventoryBook'])){
      if(isset($_POST['add']) && is_array($_POST['add'])){
     $arr = array();
         foreach($_POST['add'] as $checkbox){
            $temp = explode("_", $checkbox);

            $arr[] = array(
               "isbn"       => $temp[0],
               "condition"      => $temp[1],
               "sub_condition"  => $temp[2]
            );
         }              
     $this->addInventoryBook($arr); 
      }

      else{
         echo "No values have been set";
      }
 }


function addInventoryBook($arr){
   foreach($arr as $elem){
      //if used get sub-category
      if($elem['condition']=='used'){
         echo $elem['isbn']."-".ucfirst($elem['condition'])
            .ucfirst($elem['sub_condition'])."<br>";
      }

      else if($elem['condition']=='new'){
         echo $elem['isbn']."-".ucfirst($elem['condition'])."<br>";
      }

   }
}

All I want is to basically be able to pass two arrays to my php script

我想要的只是基本上能够将两个数组传递给我的 php 脚本

current output

电流输出

100001
100002
100003

desired output

期望的输出

100001   good
100002   new
100003   new

回答by DaveRandom

The problem that you are having, I suspect, is that only the checkboxes that are checked will be passed back to the server, whereas allthe hidden fields will always be passed so the lengths of the arrays will differ and the keys wont correspond.

我怀疑您遇到的问题是只有被选中的复选框才会被传递回服务器,而所有隐藏字段将始终被传递,因此数组的长度会有所不同并且键不会对应。

The solution to this is actually relatively simple - you just need to specify the keys for the conditionarray so you can match the values up again. Something like this:

对此的解决方案实际上相对简单 - 您只需要指定condition数组的键,以便您可以再次匹配这些值。像这样的东西:

HTML:

HTML:

  <tr>
     <td>
        <input type='hidden' name='condition[100001]' value='good' />
        <input type='checkbox' name='delete[]' value='100001' />
     </td>
  </tr>

  <tr>
     <td>
        <input type='hidden' name='condition[100002]' value='new' />
        <input type='checkbox' name='delete[]' value='100002' />
     </td>
  </tr>

PHP:

PHP:

foreach ($_POST['delete'] as $delete) {
  $condition = $_POST['condition'][$delete];
  // Do stuff
}

This ties the values in the $_POST['condition']array back up with the $_POST['delete']array so everything will match up again.

这会将$_POST['condition']数组中的值与数组联系起来,$_POST['delete']这样一切都会再次匹配。

EDIT

编辑

The way the keys are being created above is not great and in retrospect it is the wrong way to do it.

上面创建密钥的方式不是很好,现在回想起来,这是错误的方式。

To demonstrate the rightway to do it, let's imagine we have the following array, nice and simple:

为了演示正确的方法,让我们假设我们有以下数组,漂亮而简单:

$books = array(
  10001 => 'good',
  10002 => 'new',
  10003 => 'new',
  10004 => 'good'
);

What we need to do is tie up the two inputs that are associated with each book, which means we need a set of key/value pairs that can be matched up. That sounds like an array to me. But unlike the example above, the keys should be irrelevant to the data - they don't need to mean anything, because all we want is the data.

我们需要做的是将与每本书关联的两个输入联系起来,这意味着我们需要一组可以匹配的键/值对。对我来说,这听起来像是一个数组。但与上面的例子不同的是,键应该与数据无关——它们不需要有任何意义,因为我们想要的只是数据。

What we need to do is specify every single key explicitly (no stack-style array pushes) and make the keys agnostic of the data they relate to.

我们需要做的是明确指定每个键(没有堆栈样式的数组推送)并使键与它们相关的数据无关。

We can do this:

我们可以完成这个:

$i = 0;
foreach ($books as $isbn => $condition) {
  echo "
    <tr>
      <td>
        <input type='hidden' name='condition[$i]' value='$condition' />
        <input type='checkbox' name='delete[$i]' value='$isbn' />
      </td>
    </tr>
  ";
  $i++;
}

...and then, when the form is submitted, we can do this:

...然后,当表单提交时,我们可以这样做:

// We still base our code on $_POST['delete'] - because this is the array that
// depends on the user input. This time, though, we'll look at the keys as well
foreach ($_POST['delete'] as $key => $isbn) {
  $condition = $_POST['condition'][$key];
  // Do stuff
}

回答by Tabetha Moe

I'm a little confused about what you are asking, but I think I can simplify this for you. I don't know how you are generating the values for the hidden fields, are they hard coded? Regardless, this system would work much better if it were simplified.

我对您要问的内容有些困惑,但我想我可以为您简化一下。我不知道你是如何为隐藏字段生成值的,它们是硬编码的吗?无论如何,如果简化这个系统,它会工作得更好。

Try this out....

试试这个....

This will combine the info for the numbers and condition, then it will split them on the backend for handling. This way the information is passed at the same time.

这将结合数字和条件的信息,然后将它们拆分到后端进行处理。这样,信息是同时传递的。

<tr>
         <td>
            <input type='checkbox' name='delete[]' value='100001-good' />
         </td>
      </tr>

      <tr>
         <td>
            <input type='checkbox' name='delete[]' value='100002-new' />
         </td>
      </tr>

      <tr>
         <td>
            <input type='checkbox' name='delete[]' value='100003-new' />
         </td>
      </tr>

    <?php


       if(isset($_POST['deleteInventoryBook'])){
          if(isset($_POST['delete']) && is_array($_POST['delete'])){
             foreach($_POST['delete'] as $checkbox){
               $checkbox = explode('-', $checkbox);
               echo $checkbox[1];
               echo '<br />';
               echo $checkbox[0];
               echo '<br />';
             }
          }else{
             echo "No values have been set";
          }
       }


    ?>

Again, I don't know if this is helpful or not because I was a little misunderstood about what exactly you were trying to achieve, but I hope it was helpful.

同样,我不知道这是否有帮助,因为我对您想要实现的目标有一点误解,但我希望它有所帮助。

回答by David

You're going to have to find a creative way to pass multiple hidden fields as an array to the PHP handler, or change how that data is collected. A "serialized" array seems to be the best bet.

您将不得不找到一种创造性的方法将多个隐藏字段作为数组传递给 PHP 处理程序,或者更改收集数据的方式。“序列化”数组似乎是最好的选择。

This StackOverflow answerreally outlines what you can do, and should still match your script's behavior. Good luck!

这个 StackOverflow 答案确实概述了您可以做什么,并且仍然应该与您的脚本的行为相匹配。祝你好运!