如何在PHP中添加数组?

时间:2012-04-25 18:58:15

标签: php

我正在做以下但是它不起作用。无论添加多少

,它在数组中只有1个项目

有人可以告诉我我做错了吗

session_start();

$pid = mysql_real_escape_string(trim($_GET["pid"]));
$price = mysql_real_escape_string(trim($_GET["price"]));
$quantity = mysql_real_escape_string(trim($_GET["quantity"]));

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();

    $_SESSION['cart']['pid'] = $pid;
    $_SESSION['cart']['total_price'] = $price;
    $_SESSION['cart']['total_items'] = $quantity;

}else{
    $_SESSION['cart']['pid'] = $pid;
    $_SESSION['total_price'] += $price;
    $_SESSION['total_items']  += $quantity;
}

4 个答案:

答案 0 :(得分:1)

看起来您只是重置数组中的值。每次设置$ _SESSION ['cart'] ['pid']时,你都会重写最后一个值。但是,你的total_price和total_quantity可能正确递增吗?

请改用$_SESSION['cart']['pid'][] = $pid;。您需要一个'pid'数组,以便您可以拥有多个项目。 []运算符告诉php将值视为数组,并将新值推送到数组的末尾。

编辑:您在if下的初始化应如下所示,以便您的['pid']是一个pid数组:

$_SESSION['cart'] = array();
$_SESSION['cart']['pid'] = array(); //this might be redundant...but I always initialize my variables
$_SESSION['cart']['pid'][] = $pid;
$_SESSION['cart']['total_price'] = $price;
$_SESSION['cart']['total_items'] = $quantity;

else下你会得到:

$_SESSION['cart']['pid'][] = $pid;
$_SESSION['cart']['total_price'] += $price;
$_SESSION['cart']['total_items'] += $quantity;

注意:您忘记了[{1}}下的total_price和total_items上的['cart'],如其他答案所述。

答案 1 :(得分:0)

看起来你忘了将['cart']添加到底部的两个$ _SESSION setter:

$_SESSION['total_price'] += $price;
$_SESSION['total_items']  += $quantity;

更改为

$_SESSION['cart']['total_price'] += $price;
$_SESSION['cart']['total_items']  += $quantity;

答案 2 :(得分:0)

$_SESSION['cart']['pid'] = $pid; 
$_SESSION['total_price'] += $price; 
$_SESSION['total_items']  += $quantity; 

你在其他声明中忘了['cart'] ..应该是:

$_SESSION['cart']['pid'] = $pid; 
$_SESSION['cart']['total_price'] += $price; 
$_SESSION['cart']['total_items']  += $quantity; 

答案 3 :(得分:0)

你在else语句的最后一个会话变量中忘了['cart']。

请参阅this以获取php中的数组引用函数列表。