我无法将变量分配给$_SESSION
数组中的数组。
看起来它正在分配,但是当我在程序结束时执行print_r时,$_SESSION
变量看起来没有变化。
这是代码。
<?php
session_start();
print_r($_SESSION[cart_array]);
$NewGroupName="NewGroupName";
foreach($_SESSION[cart_array] as $row) {
if ($row['groupId'] == "26141"){
echo "The initial GroupName is" . $row['GroupName'] . "<br>";
echo "The GroupName should be " . $NewGroupName."<br>";
$row['GroupName'] = $NewGroupName;
echo "The actual GroupName is " . $row['GroupName']."<br>";
}
}
print_r($_SESSION[cart_array]);
?>
第一个print_r
:
Array ( [0] => Array ( [groupId] => 26141 [GroupName] => 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor] => A-CF-10 [Price] => 5.65 [StandardPutUp] => 320 [Discount] => 0 [DiscountText] => [StkUnit] => YDS [ListPrice] => 5.65 [Quantity] => 1 [PromiseDate] => 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName] => 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) [] => Array ( [DoNotShipBefore] => ) )
这种分配似乎有效:
The initial GroupName is'Crystal Farm - Ten Yard Case Pack'
The GroupName should be NewGroupName
The actual GroupName is NewGroupName
但是,最终的print_r显示我们没有更改GroupName的值。
Array ( [0] => Array ( [groupId] => 26141 [GroupName]
=> 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor]
=> A-CF-10 [Price]
=> 5.65 [StandardPutUp]
=> 320 [Discount]
=> 0 [DiscountText]
=> [StkUnit]
=> YDS [ListPrice]
=> 5.65 [Quantity]
=> 1 [PromiseDate]
=> 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName]
=> 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) []
=> Array ( [DoNotShipBefore] => ) )
任何帮助都将不胜感激。
答案 0 :(得分:4)
您不能在代码中的任何位置更改$_SESSION
。 foreach
只公开每个元素的副本。您可以使用引用&
更改它:
foreach($_SESSION['cart_array'] as &$row) {
另请注意,字符串索引$_SESSION['cart_array']
需要引号。如果您有错误报告,您会看到通知 未定义常量:cart_array。
答案 1 :(得分:0)
来自php.net:
为了能够直接修改循环中的数组元素,在$ value之前加上&amp ;.在这种情况下,该值将通过引用分配。
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>