tmartin314
tmartin314

Reputation: 4171

Remove item from multidimensional array php

Here is the array:

 [cart] => Array
        (
            [ProductId] => Array
                (
                    [0] => P121100001
                    [1] => P121100002
                )

            [SellerId] => Array
                (
                    [0] => S12110001
                    [1] => S12110001
                )

            [SpecifyId] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [Quantity] => Array
                (
                    [0] => 1
                    [1] => 1
                )

            [Price] => Array
                (
                    [0] => 12
                    [1] => 29
                )

            [TotalPrice] => 41
        )

I have the ProductId and I want to remove all the other items matching P121100002's key.

Is there an easy way to do this I can't can seem to come up with one?

Upvotes: 0

Views: 1457

Answers (3)

Robert
Robert

Reputation: 10380

Use array_key_exists along with the unset() function

Upvotes: 0

newfurniturey
newfurniturey

Reputation: 38416

You can loop through the full array and use unset() to, well, "unset" the specified index:

$index = array_search($cart['ProductId'], 'P121100002');
if ($index !== false) {
    foreach ($cart as $key => $arr) {
        unset($cart[$key][$index]);
    }
}

The slight caveat to this approach is that it may disrupt your index orders. For instance, say you have:

[ProductId] => Array (
    [0] => P121100001
    [1] => P121100002
    [2] => P121100003
)

And you want to remove P121100002, which has a corresponding index of 1. Using unset($cart['ProductId'][1]) will cause your array's to become:

[ProductId] => Array (
    [0] => P121100001
    [2] => P121100003
)

This may be something to remain concerned with if you're going to use a for loop to iterate through in the future. If it is, you can use array_values() to "reset" the indexes in the unset() loop from above:

foreach ($cart as $key => $arr) {
    unset($cart[$key][$index]);
    $cart[$key] = array_values($cart[$key]);
}

Upvotes: 3

nkr
nkr

Reputation: 3058

foreach($yourArray['ProductId'] as $key => $value) {
    if ($value == $productIdToRemove) {
        foreach($yourArray as $deleteKey => $deleteValue) {
            unset($yourArray[$deleteKey][$key]);
        }
        break;
    }
}

Upvotes: 2

Related Questions