如何合并三个数组并插入多行

时间:2020-03-05 10:30:14

标签: php mysql pdo

我有3个数组,我想实现的是,使用foreach循环,我想在数据库中插入多行。 这是我正在尝试的代码。

$array1 = ('Hello First row', 'Hello Second Row', 'Hello third row', 'Hello Forth row');
$array2 = ('This going to be First row', 'This going to be Second Row', 'This going to bethird row', 'This going to beForth row');
$array3 = ('also the first row', 'also the Second Row', 'also the third row', 'also the Forth row');
$stmt = $db->prepare("INSERT INTO table_name(first, second, third) VALUES (:first, :second, :third)");
$stmt->execute(array(':first' => $array1, ':second' => $array2, ':third' => $array3));

PS:我试图在$ stmt execute函数的正上方使用foreach循环,但是没有按预期工作。它在表中创建了12行。假设只有4个。

1 个答案:

答案 0 :(得分:-1)

$array1 = ('Hello First row', 'Hello Second Row', 'Hello third row', 'Hello Forth row');
$array2 = ('This going to be First row', 'This going to be Second Row', 'This going to bethird row', 'This going to beForth row');
$array3 = ('also the first row', 'also the Second Row', 'also the third row', 'also the Forth row');
$stmt = $db->prepare("INSERT INTO table_name(first, second, third) VALUES (:first, :second, :third)");

for($index=0; $index<count($array1); $index++) {
    $stmt->execute(array(':first' => $array1[$index], ':second' => $array2[$index], ':third' => $array3[$index]));
}