0

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?

3 Answers 3

3

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Use array_key_exists along with the unset() function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.