douxing9641 2017-04-30 17:12
浏览 48
已采纳

如何获取$ _POST数组的所有元素[重复]

This question already has an answer here:

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 />';
  }}

OUTPUT of post array print_r($_POST) looks like this (inputs has been loaded)

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)

MY OUTPUT:

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

I WANT OUTPUT:

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

In for loop I want to print only items with value of array qty>0 and it only showed qty in output. How I do print items with qty>0 together with msrp and model ? Thanks

</div>
  • 写回答

1条回答 默认 最新

  • doushouj966020 2017-04-30 17:44
    关注

    You'll need to take the index value from the key then concatanate it with the other indices to get your values. Using an array as the names in HTML would be easier.

    Current approach:

    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] ;
         }
    }
    

    The alternative, and I think cleaner, approach would be:

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

    Then iterate over it:

    foreach($_POST['qty'] as $key => $qty) {
          echo 'qty = ' . $qty . "<br> model = " . $_POST['model'][$key];
          //etc....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程