dsf11t5u1651 2018-05-24 14:12
浏览 415
已采纳

如何删除foreach循环中的最后一个值

I have a dynamic multi input. When submit form, inserting array values. But I want to insert without 'submit' value. This is the foreach loop, (sql secure not included)

if (isset($_POST['submit'])) {
    $nearest = $db->prepare('insert into nearest set place=?, distance=?');
    $i = 0;
    foreach ($_POST as $val) {
        $place = $_POST['place'][$i];
        $distance = $_POST['distance'][$i];
        $nearest->execute([$place, $distance]);
        $i++;
    }
}

This loop inserted '$_POST' values and inserted empty row.

  • 写回答

2条回答 默认 最新

  • douxiong0668 2018-05-24 14:16
    关注

    If you want to keep the loop you can use array_slice to not include the last item in the loop.
    Array_slice will take items from 0 (not literal, but the first item) to second to last (-1).
    http://php.net/manual/en/function.array-slice.php

    EDIT; I think you need a for loop to loop the count of "place".

    if (isset($_POST['submit'])) {
      $nearest= $db -> prepare('insert into nearest set place=?, distance=?');
      for($i=0; $i< count($_POST['place']; $i++){
          $place = $_POST['place'][$i];
          $distance= $_POST['distance'][$i];
          $nearest-> execute([$place , $distance]);
          $i++;
      }
    }
    

    example: https://3v4l.org/F47ui

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 全书网Java爬取数据
  • ¥15 SAP HANA SQL Script 。SUM OVER 怎么加where
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 安卓qpython向ksweb服务器post文件失败
  • ¥15 MATLAB和mosek的求解问题