在 PHP 中的数组列表中更改单个数组的值



我试图做的是通过获取数组的唯一产品ID来更改数组列表中单个数组的值(我用于在会话中保存产品)。

我正在使用以下代码:

function removeProductFromBasket($itemID)
{
// Loop through products
foreach($_SESSION['shopping_cart'] as $arr => $prod) {
// Check if product is already included
if ($prod['productid'] == $itemID) {
echo $itemID;
$_SESSION['shopping_cart'][$arr]['quantity'] = 0;
}
}
}

我的数组看起来像这样:

Array ( [0] => Array ( [productid] => 18 [quantity] => 0 ) [1] => Array ( [productid] => 2 [quantity] => 0 ) [2] => Array ( [productid] => 4 [quantity] => 4 ) ) 

当前正在使用调用该函数

href="'.removeProductFromBasket($productID).'"

分离关注点

我在当前实现中看到的第一个问题是它"神奇地"作用于$_SESSION变量。通过这样做,您将来修改逻辑的能力受到限制,因为逻辑的嵌入与数据的存储方式密切相关。您还冒着忘记代码中其他地方的函数的风险,该函数也改变了$_SESSION的值,从而使removeProductFromBasket的行为不可预测且容易受到错误的影响。

要解决此问题,您需要将函数与$_SESSION分离。您可以通过向函数签名添加一个参数来实现此目的,该参数将购物车作为数组。

function removeProductFromBasket($cart, $itemID)
{
// Loop shopping cart
foreach($cart as $key => $productArr) {
// Check if product is already included
if ($productArr['productid'] == $itemID) {
echo $itemID;
$cart[$key]['quantity'] = 0;
}
}
return cart;  // return the updated cart
}

通过以这种方式修改代码,您可以在其他位置处理$_SESSION,可能是在包装对象或类似的东西中,而不会影响购物车项目删除的逻辑。它还允许您更轻松地更改信息的持久化方式。假设您想要使用 Redis 或其他一些数据存储,那么要修改以进行更改的行将减少。

调用函数

我在您当前的实现中看到的另一个问题是调用函数的方式。从您的示例代码中,我猜测整行类似于以下内容:

echo '<a href="'.removeProductFromBasket($productID).'">Remove this</a>

由于 PHP 是在服务器端执行的,因此它所做的是在页面加载时removeProductFromBasket调用函数。这意味着,当页面在客户端呈现和加载时,该项已被删除,并且 href 对于函数中的echo来说看起来像href="12345"du。

相反,您应该将有效的 URL 回显到项目删除逻辑,并将项目 ID 作为参数正确连接。

形式.php

foreach($_SESSION['shoppingCart'] as $key => $item) {
echo '<a href="http://www.example.com/path/to/file.php?itemId='.$item['productid'].'">Remove this</a>
}

item_removal.php

<?php
// Make sure the session is started, $_GET is not empty and any other validation
function removeProductFromBasket($cart, $itemID)
{
// Loop shopping cart
foreach($cart as $key => $productArr) {
// Check if product is already included
if ($productArr['productid'] == $itemID) {
// the echo is no longer needed
$cart[$key]['quantity'] = 0;
}
}
return cart;  // return the updated cart
}
$_SESSION['shoppingcart'] = removeProductFromBasket($_SESSION['shoppingcart'], $_GET['itemId']);
?>

当然,仍有改进的余地,例如,通过围绕$_SESSION变量创建一个对象ShoppingCart和一个包装器Session,但这应该是您开始和构建的好地方。

最新更新