【问题标题】:php: Use different arrays in foreach loopphp:在 foreach 循环中使用不同的数组
【发布时间】:2015-08-15 10:05:14
【问题描述】:

我有 3 个可以动态添加的输入。所以输入的name 是数组,比如:

<input type="text" name="qty1[]">
<input type="text" name="qty2[]">
<input type="text" name="qty3[]">

(这些输入文本中的每一个都可以通过javascript生成)

在我的 php 文件中,我得到它们并想要插入到数据库(我在 codeigniter 中的控制器):

$address = $this->input->post("qty1");
$LocX =    $this->input->post("qty2");
$LocY =    $this->input->post("qty3");

在我的数据库部分,我想使用foreach 并添加到数据库:

编辑

foreach ($address as $key) {
  // I want to add $LocX and $LocY to the table
  // LocX and LocY are column names.
  $query = $this->db->query("INSERT INTO address (Comp_ID, Value, LocX, LocY)
                             VALUES(?, ?)", array($Comp_ID, $key ,? ,?));
}

我想将它们全部添加到 foreach 作为参数。正如我搜索的那样,这是不可能的。我该怎么办?谢谢。

编辑2

数组的结果,例如$LocX

Array
(
  [0] => test1
  [1] => test2
  [2] => test3
)

【问题讨论】:

  • “全部添加”和“作为参数”是什么意思?
  • @VladimirSerykh $address$LocX$locY,所有这些变量都是数组。我应该在 foreach 中使用它们以便插入数据库。
  • @MattHB 是的,类似的。
  • 您希望阵列的预期输出是什么?在插入数据库之前?
  • array_merge() 在这种情况下是不可取的,因为它会覆盖键

标签: php arrays codeigniter foreach


【解决方案1】:

您可以使用 foreach 中的索引来获取其他元素。但是你需要仔细检查其他数组中是否存在索引值(isset检查)

例如:

foreach ($address as $key => $value) {
  if(isset($LocX[$key], $LocY[$key]) {
      $a_LocX = $LocX[$key]; // This will be the locx of the address
      $a_LocY = $LocY[$key]; // This will be the locy of the address

      // Change your query to fit the table and fill in the locx and y.
      $query = $this->db->query("INSERT INTO address (Comp_ID, Value)
                             VALUES(?, ?)", array($Comp_ID, $key));
}

【讨论】:

    【解决方案2】:

    您也可以为此使用for 循环。

    $address = $this->input->post("qty1");
    $LocX =    $this->input->post("qty2");
    $LocY =    $this->input->post("qty3");
    
    $n=count($address);
    for($i=0;$i<$n;$i++){
           $a=$address[$i];
           $x=$locX[$i];
           $y=$locY[$i];
           //insert here
    }
    

    【讨论】:

      【解决方案3】:

      我会建议你使用 Codeigniter 语法,这将使你的插入工作,

      foreach($address as $k => $v)
      {
          $insert = array(
                      'Comp_ID' => $Comp_ID,
                      'Value' => $v,
                  ); // insert array
      
          if(in_array($LocX[$k], $LocX)) // existance check
              $insert = array_merge($insert, array('LocX' => $LocX[$k]));
      
          if(in_array($LocY[$k], $LocY)) // existance check
              $insert = array_merge($insert, array('LocY' => $LocY[$k]));
      
          $this->db->insert('address', $insert); // No need to write full query
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-09
        • 2020-05-17
        • 1970-01-01
        • 2013-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        相关资源
        最近更新 更多