PHP:如何替换多个 $_SESSION 数组值
第一次制作 PHP/XML 购物车,并且在更新购物车功能时遇到问题。我有一个 $quantities 数组,需要更新 $_SESSION["cart"] 值。现在,$quantities 数组中的最后一个数量正在替换所有 $_SESSION["cart"] 值,而不是第一个 $quantities 值替换第一个 $_SESSION["cart"] 值,第二个值替换第二个值,依此类推下面是一个简单的示例,显示了我的问题和我遇到问题的代码。
print_r($SESSION["cart"]);
print_r($quantities);
foreach($quantities as $index=>$quantity)
{
foreach($_SESSION["cart"] as $key=>$value)
{
$newcart = str_replace($value, $quantity, $_SESSION["cart"]);
}
}
print_r($newcart);
结果是:
Array ( [Pizzas.Tomato & Cheese.Small] => 1 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 1 )
Array ( [0] => 3 [1] => 4 )
Array ( [Pizzas.Tomato & Cheese.Small] => 4 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 4 )
我怎样才能得到最后一个数组($newcart)
Array ( [Pizzas.Tomato & Cheese.Small] => 3 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 4 )
?谢谢。
First time making a PHP/XML shopping cart and am having trouble with the update cart feature. I have a $quantities array that needs to update the $_SESSION["cart"] values. Right now, the last quantity in the $quantities array is replacing all the $_SESSION["cart"] values, as opposed to the first $quantities value replacing the first $_SESSION["cart"] value, second replacing the second, etc. Below is a simple example showing my problem and the code I'm having trouble with.
print_r($SESSION["cart"]);
print_r($quantities);
foreach($quantities as $index=>$quantity)
{
foreach($_SESSION["cart"] as $key=>$value)
{
$newcart = str_replace($value, $quantity, $_SESSION["cart"]);
}
}
print_r($newcart);
which results in:
Array ( [Pizzas.Tomato & Cheese.Small] => 1 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 1 )
Array ( [0] => 3 [1] => 4 )
Array ( [Pizzas.Tomato & Cheese.Small] => 4 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 4 )
How can I get that last array ($newcart) to be
Array ( [Pizzas.Tomato & Cheese.Small] => 3 [Homemade Lasagna Ravioli or Manicotti.With Sausage.One Size] => 4 )
? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
array_combine
:Use
array_combine
: