如何获取$ _POST数组的所有元素

时间:2017-04-30 17:12:07

标签: php html

HTML

    //index.php
   <form name="test" action="form.php" method="post"> 
     name="model<?php echo $key ?>"
     name="qty<?php echo $key ?>"
     name="msrp<?php echo $key ?>"
    </form>

PHP

  foreach($_POST as $key => $value) {
 //I want to print only items with qty>0
 if (("qty" == substr($key, 0, 3) && $value > 0))
  {     
     echo $key, ' => ', $value,  '<br />';
  }}

发布数组的输出     print_r($ _ POST)看起来像这样(已加载输入)

Array([model1] => FSE 30 [msrp1] => 129.95 [qty1]=1
[model2] => FS 38 [msrp] => 129.95 [qty2]=3
[model3] => FS 60 [msrp] => 159.95 [qty3]=4
[model4] => FS 70 [msrp] => 169.95 [qty4]=0)

我的输出:

qty1 => 1
qty2 => 3
qty3 => 4

我想要输出:

   model1 =>FS 30 qty1 => 1 msrp=>129.95
   model2 => FS 38 qty2 => 3 msrp=> 129.95
   model3 => FS 60 qty3 => 4 msrp=> 159.95

在for循环中我想只打印数值为qty&gt; 0 的项目,并且它只显示输出中的qty。如何使用qty&gt; 0和 msrp和模型打印项目?感谢

1 个答案:

答案 0 :(得分:1)

您需要从key获取索引值,然后将其与其他索引连接起来以获取您的值。使用数组作为HTML中的名称会更容易。

目前的做法:

foreach($_POST as $key => $value) {
    if (("qty" == substr($key, 0, 3) && $value > 0)) {     
         $id = substr($key, 3);
         echo 'qty' . $id . ' => ' . $value . 
             'model' . $id . ' => '. $_POST['model' . $id] .
             'msrp' . $id . ' => ' . $_POST['msrp' . $id] ;
     }
}

替代方案,我认为更清洁,方法是:

<form name="test" action="form.php" method="post"> 
     name="model[]"
     name="qty[]"
     name="msrp[]"
     name"id[]" type="hidden" value="<?php echo $key;?>"
    </form>

然后迭代它:

foreach($_POST['qty'] as $key => $qty) {
      echo 'qty = ' . $qty . "<br> model = " . $_POST['model'][$key];
      //etc....
}