2013-03-26 156 views
-2

我试图让这个嵌套的foreach循环工作,但我没有运气。这是我的代码。嵌套的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数组中的第一个值。我该如何解决?这是您请求的数组。

项目数组和数量数组。

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') 
+0

在你做任何事之前,看看你的代码中看起来有什么大的SQL注入漏洞。 – 2013-03-26 21:24:30

+1

我知道的sql问题。我只想让循环先在我的本地环境中工作。 – wowzuzz 2013-03-26 21:25:17

+1

向我们展示你的'items'和'quantity'数组? – MichaelRushton 2013-03-26 21:27:57

回答

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>'; 
} 
+0

我不知道我可以在这个循环内循环通过我的数量。很高兴知道MichaelRushton。感谢球员的所有帮助! – wowzuzz 2013-03-26 21:45:03

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]."')"; 
} 

沿着你所需要的线条更。

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... 

}