【问题标题】:How to store alternate values from two array using for each loop php如何使用每个循环php存储两个数组中的备用值
【发布时间】:2019-08-08 11:35:16
【问题描述】:

我创建了两个数组,我想在数据库表中添加备用值

foreach($aaa[$key] as $key2 and $bbb[$key] as $key3) {
  $qd = "INSERT INTO aaa (xxx, yyy, status) VALUES ('$key2', '$key3', '1')";
  $dd = mysqli_query($conn, $qd);
  if ($dd) {
    echo '1';
  } else {
    echo mysqli_error($conn);
  }
}

【问题讨论】:

  • 不清楚你想达到什么目的...你能解释得更好并添加例子吗?
  • 如果您向我们展示了您上面提供的所有内容的确切反面,我认为问题会更清楚

标签: php mysql arrays mysqli foreach


【解决方案1】:

因此,您希望为您的数组设置 2 个循环,这些循环都将用于您的查询。您可以在循环中使用索引。

// count of items. from what you wanted to do to your loop
// it looks like it is given that the count of 2 arrays are
// the same.
$count = count($aaa[$key]);

for ($i = 0; $i < $count; $i++) {
    $qd = "INSERT INTO aaa (xxx, yyy, status) VALUES ($aaa[$key][$i], $bbb[$key][$i], '1')";
    $dd = mysqli_query($conn, $qd);

    if ($dd) {
        echo '1';
    } else {
        echo mysqli_error($conn);
    }
}

【讨论】:

  • 我认为for 循环条件将是$i &lt; $count...否则它永远不会执行循环体
  • @dWinder 是的。抱歉没能抓住。我在想的是
  • 还是不行 - 你不能访问最后一个元素,因为 $count 它必须是 $count-1 所以 $i &lt; $count$i &lt;= ($count-1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
相关资源
最近更新 更多