简体   繁体   中英

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.

$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

I have tried using a foreach loop, which will find the value but I seem unable to get back to the key

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 .

I think this is what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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