根据本论坛的合理建议,我正在重写涉及多维数组SESSIONS购物车的代码,以便产品ID是数组名称(我认为我正确地解释了这一点)。我可以向数组中添加,但不能删除任何东西。我正在使用一个数组来添加新的项目数据到SESSIONS数组。下面的代码表示一个向数组添加项目的测试,最后尝试删除一个项目,但失败了。如能帮助找出我的错误,我将不胜感激。
echo '************** STEP ONE **********************';
// Initialize array
$_SESSION['cart'] = array();
// Array of newitem
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with one item
var_dump($_SESSION['cart']);
echo '************** STEP TWO **********************';
// Array of newitem
$id = 33;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7170-11',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with two items
var_dump($_SESSION['cart']);
echo '************** STEP THREE **********************';
// Array of newitem
$id = 34;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7171-15',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with three items
var_dump($_SESSION['cart']);
echo '************** STEP FOUR **********************';
// Unset by ID
$id = 34;
unset($_SESSION['cart'][$id]);
// Display cart array with two items
var_dump($_SESSION['cart']);
当您使用$_SESSION['cart'][]
时,它会动态地使用下一个索引添加一个新的数组项。然后在这个数组下面再添加两个数组。尝试使用特定的$id
:
$id = 181;
$newitem = array(
'quantity' => 1,
'part_number' => '600N5630-501',
);
// Add newitem to cart
$_SESSION['cart'][$id] = $newitem;
或者你可以像这样添加/替换它们:
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'] = array_replace($_SESSION['cart'], $newitem);