我在 PHP 中更新多维数组时遇到问题。我正在尝试为一个项目实施电子商务网站,但在实施购物车时遇到问题。
基本上,我使用会话来跟踪用户添加到购物车的项目。这是我在纯伪代码中的逻辑,一旦用户在指定要为产品添加的数量后单击添加按钮,就会执行该逻辑:
从会话数组中检索"购物车项目"2D 数组
如果会话中不存在"cartItems"数组,则创建新的空数组,并使用 qty 和 productID 向其添加 cartItem 子数组
ELSE 遍历从 SESSION 数组检索的数组,找到与给定产品 ID(索引 0)匹配的产品 ID,并更新该子数组的数量(索引 1)。
这是我的PHP脚本addToCart.php它反过来调用包含在其中的另一个脚本文件中的另一个函数:
<?php
require_once("cart_utility.php");
session_start();
// Script for adding a given product to the client's cart through the use of Ajax and sessions
// retrieve values from ajax request
$productID = $_GET["productID"];
$qty = $_GET["qty"];
$cartItems = null;
// use sessions to add the items to the user's cart
// retrieve the multi-dimensional cart array if it exists, otherwise create one and add it
if(isset($_SESSION["cartItems"])){
$cartItems = $_SESSION["cartItems"];
}
else{
$cartItems = array();
}
addQtyForProduct($productID, $qty, $cartItems);
$_SESSION["cartItems"] = $cartItems;
print "Session cartItems after function return: ";
var_dump($_SESSION["cartItems"]);
// return info string with new qty of cart items
print ("success-" . getTotalCartItems($cartItems));
?>
下面是另一个脚本文件,用于处理插入和更新数组:
<?php
// Utility functions for retrieving items from the 2D cart items array
/* The array structure is given as (example values):
* | productID | qty |
* 0 | 1 | 3 |
* 1 | 2 | 1 |
* 2 | 5 | 8 |
* 3 | 8 | 3 |
*/
// increments the qty for the given product. If it does not exist then it is added into the main session array
// $cartItems: the main 2D array with the structure given above, pass by reference to change the array
function addQtyForProduct($productID, $qty, &$cartItems)
{
foreach($cartItems as $cartItem)
{
var_dump($cartItem);
if($cartItem[0] == $productID){
//print "Quantity given to increment: $qty";
//var_dump($cartItem);
print "Qty in current session array: $cartItem[1]";
$cartItem[1] += $qty;
print "New qty in cartItem array: $cartItem[1]";
return;
}
}
// not found, therefore add it to the main items array
array_push($cartItems, array($productID, $qty));
}
// returns the total number of items in the cart
function getTotalCartItems($cartItems)
{
$total = 0;
foreach($cartItems as $cartItem)
$total += $cartItem[1];
return $total;
}
?>
我已经放置了一些var_dump语句,并且可以确认从函数"addQtyForProduct"返回后,数组不会更新。但是为什么?我通过引用传递数组以直接更改其内容。
当没有现有数组时,它会在第一次成功添加,但如果数组存在,则无法递增。
此外,这些值在"addQtyForProduct"函数中成功递增,但数组在从函数返回时不知何故没有更新。
我很乐意在这方面得到一些帮助。几天来我一直在试图理解这一点,这让我发疯。
正如本页所读的,您应该使用参考文献。在$cartItem
前面添加一个&
,您的脚本应该可以工作。现在PHP将数组中每个值的"副本"存储在$cartItem
中,而不是它的引用。因此,当前您正在编辑原始数组的副本,而不是原始数组。