[英]Looping through a 2d session array shopping cart php
我正在搭建購物車,想使用2D數組存儲商品ID和數量。 當用戶轉到購物車時,我希望能夠從數組中獲取商品ID,並從數據庫中輸出商品詳細信息
/**************** Adding to the 2d array ***********************/
//Check to see if variable isset and then add item to shopping cart
//$itemID is the ID of the product
//$quantity is the quantity of the product they wish to order
if(isset($_GET['add'])){
$itemID = $_GET['add'];
$quantity = $_POST['quantity'];
$_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
header('xxx');//stops user contsanlty adding on refresh
}
/******************** Looping through the array **********************/
//need to loop through grab the item ID
//then pull what we need from the database
//This is where I want to grab the id from the array and query the database
$cart = $_SESSION['cart'];
foreach ($cart as $value ){
//works like it should
foreach ( $value as $key=> $final_val ){
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
echo '<br/>';
}
數組輸出像這樣
id:1數量:5
id:2數量:1
我在弄清楚如何區分ID和數量方面有些麻煩,這樣我就可以使用項目ID來查詢數據庫。
foreach ( $value as $key=> $final_val ){
if($key=='id')
{
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
}
或者您也可以直接使用$value['id']
東西,這將對您有所幫助。請嘗試。 這是您需要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.