代码
print_r($_SESSION['itmCheck']);
输出
Array
(
[Pid] => Array
(
[0] => 8
[1] => 10
[2] => 9
)
[quantity] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
想要将所有数据保存在数据库中并以
显示此格式INSERT INTO `cart`( `p_id`, `quantity`) VALUES (pid[0],quantity[0],pid[1],quantity[1])
答案 0 :(得分:0)
我可以提出两种简单的方法来遍历您的数据。
$insertQuery = 'INSERT INTO `cart`( `p_id`, `quantity`) VALUES ';
$dataRaw = [
'Pid' => [
0 => 8,
1 => 10,
2 => 9,
],
'quantity' => [
0 => 1,
1 => 2,
2 => 3,
],
];
// Foreach with combined array
$dataCombined = array_combine($dataRaw['Pid'], $dataRaw['quantity']);
$valuesCombined = array();
foreach ($dataCombined as $key => $value) {
$valuesCombined[] = '(' . $key . ', ' . $value . ')';
}
echo $insertQuery . implode(',', $valuesCombined) . ';';
// //
echo '<br><br>';
// For loop with array index
$valuesRaw = array();
for ($i = 0; $i < count($dataRaw['Pid']); $i ++) {
$valuesRaw[] = '(' . $dataRaw['Pid'][$i] . ', ' . $dataRaw['quantity'][$i] . ')';
}
echo $insertQuery . implode(',', $valuesRaw) . ';' ;
// //
上面的代码输出:
INSERT INTO `cart`( `p_id`, `quantity`) VALUES (8, 1),(10, 2),(9, 3);
INSERT INTO `cart`( `p_id`, `quantity`) VALUES (8, 1),(10, 2),(9, 3);