我有一个结构如下的多维数组
[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 theAUTO INCREMENT
handle that for you.
关于php - 将多维数组循环到mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050638/