我正在构建一个购物车,并希望使用二维数组来存储商品 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/>';
}
数组输出像这样
编号:1 数量:5
编号:2 数量:1
我在弄清楚如何分离 ID 和数量以便我可以使用项目 ID 查询数据库时遇到了一些麻烦。