2012-04-25 73 views
-1

我正在做下列事情,但它不起作用。它只有數組中的1項不管我有多少添加如何添加到PHP中的數組?

有人可以告訴我,我做錯了什麼

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; 
} 
+3

誰給-1,甚至不打擾解釋原因留下評論?這篇文章遵循SO中的所有規則。明確的問題,OP已經付出了努力....還有什麼我錯過了? – itachi 2012-04-25 19:09:11

回答

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; 

注意:您在其他答案中提到的else下的total_price和total_items上忘記了['cart']。

0

您似乎忘記到[「購物車」]添加至底部2個$ _SESSION setter方法:

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

變化

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

你忘了你的其他statemnt的[「購物車」] ..應該是:

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

你在最後else語句的會話變量忘記[「購物車」。

請參閱this瞭解php中數組引用函數的列表。