嵌套的foreach循环问题

时间:2013-03-26 21:21:11

标签: php foreach nested

我试图让这个嵌套的foreach循环起作用,但我没有运气。这是我的代码。

$q = 0;
$arrayCountTwo = count($_POST['quantity']);
$i = 0;
$arrayCountThree = count($_POST['items']);
foreach ($_POST['items'] as $items) {
    $sql = '';
    foreach ($_POST['quantity'] as $quantity) {
        $q++;
        if ($q > $arrayCountTwo) {
            break;
        } else {
            $sql .= "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$items."','".$startDate."', '".$endDate."','".$quantity."')";
        }
        var_dump($sql);
    }   
}

它在每次迭代时不断给我$items数组中的第一个值。我该如何解决这个问题?

以下是您请求的阵列。

按顺序列出items数组和数量数组。

array(3) {
  [0]=>
  string(2) "11"
  [1]=>
  string(1) "6"
  [2]=>
  string(1) "2"
}

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "1"
}

每次都应该这样做。

INSERT INTO `ts_table` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('11','2013-4-11', '2013-4-25','1')

INSERT INTO `ts_table` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('6','2013-4-11', '2013-4-25','2')

3 个答案:

答案 0 :(得分:2)

这应该做你想要的:

foreach ($_POST['items'] as $key => $items)
{
  $sql = "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$items."','".$startDate."','".$endDate."','".$_POST['quantity'][$key]."')";
  echo $sql . '<br>'; 
}

答案 1 :(得分:0)

for($i = 0, $iMax = min(count($_POST['items']), count($_POST['quantity'])); $i < $iMax; $i++)
{
    $sql .= "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$_POST['items'][$i]."','".$startDate."', '".$endDate."','".$_POST['quantity'][$i]."')";
}

更符合您的需求。

答案 2 :(得分:0)

我认为你正在寻找这样的东西。假设item[1]quantity[1]相关;

foreach ($_POST['items'] as $idx => $item) {
    // get the quantity with the same index as the item
    // if it does not exist, default to zero
    $quantity = isset($_POST['quantity'][$idx]) ? $_POST['quantity'][$idx] : 0;

    // insert query... 

}