2014-02-05 125 views
0

我正在創建購物車應用程序。我有將每個項目添加到會話數組的邏輯,但我不知道如何將值添加到會話數組中。有人能幫助我嗎?將值添加到會話數組中

回答

5

它很簡單地爲會話數組添加值。

1.將以下行添加到腳本的頂部以啓動會話。

session_start(); 

2.使用以下示例向會話數組添加值。

$_SESSION['variable1'] = "Test1"; 
$_SESSION['variable2'] = "Test2"; 

3.檢查像下面的例子那樣的會話數組值。

//Prints whole session array by using below line 
print_r($_SESSION); 
//print individual values by using below examples 
echo isset($_SESSION['variable1']) ? $_SESSION['variable1'] : ''; 
echo isset($_SESSION['variable2']) ? $_SESSION['variable2'] : ''; 

請讓我知道如果你仍然發現任何問題

0

每個項目添加到一個數組,並將其分配給這樣

session_start(); 
$_SESSION['cart'] = array(...); 

會話變量,所以你可以訪問每一個項目像這樣

$_SESSION['cart'][0] 
$_SESSION['cart'][1] 
. 
. 
. 
0

嘗試

session_start();// First of all start session  
$_SESSION['arry_key_may_be_your_name']='My name';// Add values to session array 
+0

代碼只答案是望而卻步。請擴展您的答案以解釋您的代碼的作用以及它如何回答OP的問題。 – jwpfox

0

添加項目到會話中使用以下代碼.. PHP SESSION

<h3>PHP SESSION :Store Multiple User Info In PHP SESSION --codenair.com</h3> 
<form method="POST"> 
<table> 
    <tr> 
<td>UserName:</td> 
<td><input type="text" name="name" required/></td> 
    </tr> 
<tr> 
<td>Email</td> 
<td><input type="text" name="email" required/></td> 
    </tr> 
    <tr> 
<td></td> 
<td><input type="submit" name="submit" value="Add User"/></td> 
    </tr> 
</table> 
</form> 
<?php 
session_start(); 
if(isset($_POST['submit'])){ 
$user=array(
'name'=>$_POST['name'], //Username form field name 
'email'=>$_POST['email'] //email form field name 
); 
$_SESSION['student'][]=$user; 
} 
if(isset($_GET['remove'])){ 
unset($_SESSION['student']); 
//Redirecting After Unset SESSION 
    header('location:index.php'); 
    } 
?> 
<?php if(!empty($_SESSION['student'])){?> 
    <table class="table" cellspacing="0" border="1"> 
    <tr> 
    <th>Serial</th> 
    <th>Name</th> 
    <th>Email</th> 
    </tr> 
<?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {?> 
    <tr> 
    <td><?php echo $i;?></td> 
    <td><?php echo $_SESSION['student'][$i]['name'];?></td> 
<td><?php echo $_SESSION['student'][$i]['email'];?></td> 
    </tr> 
<?php } ?> 
</table> 
<a href="index.php?remove=remove">Empty User</a> 
<?php }else{ 
    echo "You have no User in SESSION"; 
}?>