php - 将多维数组循环到mysql中

标签 php mysql arrays

我有一个结构如下的多维数组

[nmbr] => Array
       (
           [0] => u
           [1] => t
       )
[jmlh] => Array
        (
           [0] => 4
           [1] => 6
        )

我想把它插入到一个看起来像的数据库中

id   nmbr   jmlh
1    u      4
2    t      6

我尝试使用 for 循环,但它只检测到第一个数组,第二个数组没有插入到数据库中。

这是我的for循环

$namabarang = $_POST['nmbr'];
$jumlah = $_POST['jmlh'];
for ( $i = 0; $i<$total; $i++)
{
  $nmbr = $namabarang[$i];
  $jmlh = $jumlah[$i];
  $data = array(
    'id_tender' => $primary_key,
        'nmbr' => $nmbr,
        'jumlah' => $jmlh
        );
  $this->db->insert('tb_tender_barang', $data);
}

最佳答案

如果两个数组的大小相同。一个简单的 for 循环就足够了。在您当前的代码中,您没有检查在循环中使用的它们中的任何一个的大小。考虑这个例子:

// this will just strictly work if they have the same size!
$namabarang = $_POST['nmbr'];
$jumlah = $_POST['jmlh'];

for($i = 0, $size = count($jumlah); $i < $size; $i++) {
    $data = array('id' => $i+1, 'nmbr' => $nmbr[$i], 'jmlh' => $jmlh[$i]);
    $this->db->insert('tb_tender_barang', $data);
}

Sidenote: Why do you need to manually insert the id in the table? Let the AUTO INCREMENT handle that for you.

关于php - 将多维数组循环到mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050638/

相关文章:

arrays - powershell.exe -file 字符串数组作为参数

php - 如何将父表当前主键的值插入到子表中

mysql - 如何使用流畅的 api 在 EF6 中映射值对象标识?

php - 在 MYSQL 上运行更新

php - 如何比较同一个 MySQL 表中不同行的不同列(在 php 中)?

mysql - 在 Azure 数据库中为 MySQL 创建 MyISAM 表是否启用?

javascript - 有没有办法创建变量的名称并从循环中进行更改?

C中使用递归计算数组的累加和

php - mysql中 "WHERE "和 "IN"的区别

php - html 表并用带有空行的 php 填充