首页 > 解决方案 > 需要从这个数组中提取结果

问题描述

我正在使用 JQuery 表单转发器插件 ( https://github.com/DubFriend/jquery.repeater ) 允许我的用户向表单添加额外的行。我是获得结果的一部分,但现在我很难过。文档不是那么好,所以我一直在寻找一种方法来做到这一点。

我需要从表单转发器中获取字段(通过 $_POST)并将它们分离出来并将它们添加到我的数据库中。我可以做数据库位:-)

我尝试了一些 foreach 组合来尝试从数组中获取条目,但我有点难过,对数组有点陌生!

这是表单中的 HTML...

<div class="repeater">
   <div data-repeater-list="fuelUplifts">
      <div data-repeater-item>
         <div class="row">
            <div class="col-md-12 col-lg-6">
               <div class="form-group">
                  <label for="fuelUpliftLocations">Uplifted from</label>
                  <input type="text" class="form-control" id="fuelUpliftLocations" name="fuelUpliftLocations" maxlength="45" value="<?php echo Input::get('fuelUpliftLocations'); ?>">
               </div>
            </div>
            <div class="col-md-12 col-lg-6">
               <div class="form-group">
                  <label for="fuelUpliftAmount">Amount</label>
                  <div class="input-group">
                     <input id="fuelUpliftAmount" name="fuelUpliftAmount" type="number" step="0.01" maxlength="8" class="form-control" placeholder="" value="<?php echo Input::get('fuelUpliftAmount'); ?>">
                     <div class="input-group-append">
                        <button data-repeater-delete class="btn btn-danger" data-message="yo" type="button"><i class="mdi mdi-delete-forever"></i></button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
   <input class="btn btn-primary" data-repeater-create type="button" value="Add another fuel stop"/>
</div>

如果我 print_r 数据中继器列表,我会得到以下信息

array(2) { [0]=> array(2) { ["fuelUpliftLocations"]=> string(26) "Mayflower Marina, Plymouth" ["fuelUpliftAmount"]=> string(4) "1500" } [1]=> array(2) { ["fuelUpliftLocations"]=> string(23) "Yarmouth, Isle of White" ["fuelUpliftAmount"]=> string(4) "1500" } } 

我仍在尝试了解数组以及获得结果的最佳方法。谁能指出我从“fuelUpliftLocations”和“fuelUpliftAmount”中提取数据的正确方向?

我想获取每个字段并将它们作为逗号分隔的字符串保存在数据库中各自的列中。

把它弄出来让我很难过。我尝试了一些 foreach 循环变体,例如:

  foreach ($_POST['fuelUplifts'] as $key => $value) {
    print_r($value);
  }

这返回

Array ( [fuelUpliftLocations] => Mayflower Marina, Plymouth [fuelUpliftAmount] => 1500 ) Array ( [fuelUpliftLocations] => Yarmouth, Isle of White [fuelUpliftAmount] => 1500 )  

所以我想我越来越近了。谁能指出我正确的方向?

非常感谢!

马特

标签: phparrays

解决方案


这是你想要做的吗?

foreach ($_POST['fuelUplifts'] as $row) {
  print $row['fuelUpliftLocations'];
  print $row['fuelUpliftAmount'];
}

这是未经测试的,但应该打印出每行的位置和金额。如果您需要其他格式,您现在可以控制这样做。


推荐阅读