简体   繁体   English

根据值之一在多维数组中取消设置值

[英]Unset a value in a multi-dimensional array based on one of the values

I am attempting to unset a row in a multi-dimensional array based on finding one of the values (the product code) 我试图根据找到值之一(产品代码)来取消多维数组中的行

Here is a slightly simplified structure/content of the array: 这是数组的稍微简化的结构/内容:

Array ([0] => Array ( [item_id] => code1 [item_desc] => first product  [item_price] => 5.45 )
[1] => Array ( [item_id] => code2 [item_desc] => second product  [item_price] => 9.25 ))

The following works fine except when trying to delelete the first item [0] in the array - so the first item in the basket cannot be deleted. 除试图删除数组中的第一项[0]之外,以下各项工作正常,因此无法删除购物篮中的第一项。

$pid = 'code2';

$key = array_search($pid, array_column($_SESSION['cart_array'], 'item_id'));

if($key) {
    unset($_SESSION['cart_array'][$key]);
    sort($_SESSION["cart_array"]);
    }

Where the value of $pid = 'code1', $key returns false and the session variable content remains unchanged $ pid ='code1'的值时,$ key返回false,并且会话变量内容保持不变

I have tried using a foreach loop, which will find the value but I seem unable to get back to the key 我尝试过使用foreach循环,该循环将找到值,但我似乎无法回到关键位置

foreach ($_SESSION['cart_array'] as $search)
    {
        if($pid == $search['item_id'])
        {
        echo key($search);            // returns item_id
        }
    }

Any help much appreciated. 任何帮助,不胜感激。

当使用array_search()的返回值时,它可能为第一项返回0(如您所知),并且在测试0时-这与false相同,您需要检查该键是否等于false。 。

if($key !== false) {

Use a simpler approach: 使用更简单的方法:

$_SESSION['cart_array'] = array_filter($_SESSION['cart_array'], function ($item) use ($pid) {
    return $item['item_id'] != $pid;
});

This filters all items out of the array which match $pid . 将从数组中筛选出与$pid相匹配的所有项目。

I think this is what you want. 我想这就是你想要的。

foreach ($_SESSION['cart_array'] as $key => $search)
{
    if($pid == $search['item_id'])
    {
        echo $key;
    }
}

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

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