如何为存储在会话中的关联数组添加值?

How to add value to associative array that store in session?

include('session.php');

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];    

$wishlist = array("$productname" => $productcode);      

$_SESSION["wishlist"] = $wishlist;

print_r($_SESSION["wishlist"]);

此代码设置为名为 "wishlist" 的会话的数组。
问题是会话正在被替换。如果它已经存在,我想添加到数组中。

那么我怎样才能用新数据更新我的数组。 我尝试了以下方法。

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];

// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
    $wishlist = array("$productname" => $productcode);
} else {
    /*
        How Can I Update array ???      
    */
}

数组输出是这样的。它关联的不是数字索引。 我想要单个数组的结果。不是数组中的数组。

[mobile] => iphone_2

谢谢。

简而言之,你可以这样做(如果我理解正确的话):

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];

// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
    $wishlist = array("$productname" => $productcode);
} else {
    array_push($wishlist, array("$productname" => $productcode));
}

array_push 是一个将信息添加到数组末尾的函数。在本例中,我们使用它将产品数组添加到当前愿望清单。

另一种简单的解决方案是:

// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));

// you can then access each product as:
$wishlist["mobile"];

或将上述代码片段中的第 5 行替换为以下内容:

$wishlist[$productname] = $productcode;

这将使您不必像第 3 行那样创建一个空数组。
array_push 的优势在于您可以一次添加多个产品,例如:

$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);

我注意到的一件事是您将会话设置为 $lastsession 以及使用 $wishlist。尝试让重复的变量不存在。

将会话中的心愿单数据设置为变量,然后将新产品添加到该变量。之后更新会话中的心愿单数据。

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];

// do the same as: $wishlist = !empty($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : [];
$wishlist = $_SESSION["wishlist"] ?? [];

$wishlist[$productname] = $productcode;
$_SESSION["wishlist"] = $wishlist;

print_r($_SESSION["wishlist"]);
$_SESSION["wishlist"] = array( 'product1' => 'product1 Name' );
// Initial products in session

$temp_session = $_SESSION["wishlist"];
//store products in wishlist in temp variable

$temp_session['mobile'] = 'iphone_2';
// Add new product to temp variable

$_SESSION["wishlist"] = $temp_session;
//Update session

print_r( $_SESSION["wishlist"] );