简体   繁体   English

如何从二维关联数组中取消设置/删除项目

[英]How to unset / remove item from two dimensional associative array

On sound advice from this Forum, I am re-writing code involving multi-dimensional array SESSIONS cart so that the product ID is the array name (I think I am explaining this correctly). 根据这个论坛的合理建议,我正在重新编写涉及多维数组SESSIONS购物车的代码,以便产品ID为数组名称(我想我在正确地解释了这一点)。 I can add to the array, but I cannot remove anything. 我可以添加到数组,但不能删除任何内容。 I am using an array to add new item data to the SESSIONS array. 我正在使用一个数组将新的项目数据添加到SESSIONS数组。 The code below represents a test adding items to the array and finally trying and failing to delete one. 下面的代码代表一个测试,该测试将项目添加到数组中,最后尝试删除失败。 Any assistance in finding my errors is appreciated. 感谢您为发现我的错误提供的任何帮助。

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']);

When you use $_SESSION['cart'][] it adds a new array item dynamically with the next index. 当您使用$_SESSION['cart'][]它会动态添加带有下一个索引的新数组项。 You are then adding another two arrays under that one. 然后,您要在该数组下添加另外两个数组。 Try creating the index with the specific $id : 尝试使用特定的$id创建索引:

$id = 181;
$newitem = array(
           'quantity' => 1,
           'part_number' => '600N5630-501',
);
// Add newitem to cart
$_SESSION['cart'][$id] = $newitem;

Alternately you could add/replace them like this: 或者,您可以像这样添加/替换它们:

$id = 181;
$newitem = array(
    $id => array(
        'quantity' => 1,
        'part_number' => '600N5630-501',
    )
);
// Add newitem to cart
$_SESSION['cart'] = array_replace($_SESSION['cart'], $newitem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM