我正在尝试使用数组将数据从产品页面传递到购物车页面。viewcart.php 将从上一页收到多个属性(价格、链接、标题和零售商)。我想用一个数组来保存它们。对于客户添加到购物车中的每个附加项目,我试图获取一个计数器变量 ($i) 来增加数组 $_SESSION['cart'][$i]['attribute']。我该怎么做呢?
我不确定这是将新产品添加到购物车的正确方法。最后,我想要一种能够使用 for 循环显示购物车中所有产品的方法。到目前为止,这是我在购物车脚本上的开始:
<?php
// The shopping cart needs sessions, so start one
session_start();
@$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];
if($link) {
//new item selected
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
$_SESSION['items'] = 0;
$_SESSION['total_price'] ='0.00';
}
if(isset($_SESSION['cart'][$link])) {
$_SESSION['cart'][$link]++;
} else {
$_SESSION['cart'][$link] = 1;
}
}
if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
echo " in your cart and we're working to display them";
}
else {
echo "<p>There are no items in your cart</p><hr/>";
}
?>
这是我认为可以使用的 for 循环。我正在寻找某种方法来显示数组中的所有项目。
for ($x=0; $x<=$i; $i++)
{
echo "The price is " . $_SESSION['cart'][$x][price] . " Retailer is " . $_SESSION['cart'][$x] [retailer] . "<br>";
}