我有一张表格,其中包含产品名称及其相应数量。
Product Quantity Delete
A 10 Del
B 5 Del
我想要做的是将它们放在一个具有相应产品ID的数组中。我可以获得第二个产品的产品ID,但我无法获得第一个产品的ID。我该如何解决?
这是php代码的输入表单:
<table>
<tr>
<td><input id="product1" type="text" value="A" name="product1"></td>
<td><input id="quantity1" type="text" value="10" name="quantity1>
<input type='hidden' name='htmlrow[]' value='1'> </td> //row number
</tr>
<tr>
<td><input id="product2" type="text" value="B" name="product2"></td>
<td><input id="quantity2" type="text" value="5" name="quantity2">
<input type='hidden' name='htmlrow[]' value='2'></td>//row number
</tr>
</table>
php代码:
$numberOfRows = $_POST["htmlrow"];
$r = end($numberOfRows);
for($i=1; $i<$r+1; $i++){ //r = number of rows
$results = $wpdb->get_results("SELECT * FROM wp_products WHERE productName = '".$_POST["product".$i]."'");
foreach($results as $product){
$pID = $product->productID;
} //I can only get the last product ID
$orderItem = array(
'product' => $_POST["product".$i],
'productID' => $pID,
'quantity' => $_POST["quantity".$i]
);
$order[] = $orderItem;
}
答案 0 :(得分:0)
数组从0开始而不是从1开始。当您将值1分配给$ i时,循环将从该行的第二个元素开始。播下解决方案就是这个。
for($i=0; $i<$r+1; $i++){ //r = number of rows
$results = $wpdb->get_results("SELECT * FROM wp_products WHERE productName = '".$_POST["product".$i]."'");
foreach($results as $product){
$pID = $product->productID;
} //I can only get the last product ID
$orderItem = array(
'product' => $_POST["product".$i],
'productID' => $pID,
'quantity' => $_POST["quantity".$i]
);
$order[] = $orderItem;
}
这是一个例子。让我们说我们有一个数组$ test
$test = array("A","B","C","D");
数组中的第一个元素是&#34; A&#34;和&#34; A&#34;位于第0位。&#34; B&#34;在第1位,依此类推。
在你的foreach循环中你有$ pID var来保存你的产品&#34; ID&#34;,所以$ pID总是会有$ results的最后一个元素。你必须将$ orderItem数组放在foreach循环中。
foreach($results as $product){
$pID = $product->productID;
$orderItem = array(
'product' => $_POST["product".$i],
'productID' => $pID,
'quantity' => $_POST["quantity".$i]
);
$order[] = $orderItem;
}
或者你可以试试这个
$results[$i] = $wpdb->get_results("SELECT * FROM wp_products WHERE productName = '".$_POST["product".$i]."'", ARRAY_A);
print_r($results);