带foreach循环的多维数组

时间:2018-07-04 11:49:42

标签: php

代码

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])

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);