我有这些foreach循环的问题,如果我嵌套它们输出不正确..在下面的代码中:事物将被多次添加到数据库..所以我实际上需要一个带有2个条件的foreach循环但是我不知道这是否可能?我需要将产品和数量添加到数据库中。
$keys = array_keys($_SESSION['meal1']);
foreach ($_SESSION['meal1'] as $quantity) {
foreach ($keys as $products) {
$query1 = sprintf("INSERT INTO `maaltijdproducten`(`meal_id`, `product_id`, `quantity`, `schema_id`) VALUES ('1' ,'$products', '$quantity', '$schemaid')");
$result1 = mysql_query($query1);
}
}
会话'饭1'就像:产品是指数,数量是价值:
array (size=2)
1 => int 1
7 => int 6
答案 0 :(得分:2)
如果数组相同,则不需要迭代两次。
$keys = array_keys($_SESSION['meal1']); //it contains the keys in an an array
foreach ($_SESSION['meal1'] as $quantity) { //it iterates the array and the value of each key is in $quantity.
我想你可能需要
foreach ($_SESSION['meal1'] as $current_key => $quantity) {
//$current_key -> product as you mentioned
答案 1 :(得分:0)
这可能就是你要找的东西:
$meals = $_SESSION['meal1'];
foreach($meals as $quantity => $product) {
$query1 = sprintf("INSERT INTO `maaltijdproducten`(`meal_id`, `product_id`, `quantity`, `schema_id`) VALUES ('1' ,'$product', '$quantity', '$schemaid')");
$result1 = mysql_query($query1);
}