在PHP中删除特定的多维数组元素后,Next数组元素不会自动定位

I've created the multidimensional array in the following format

Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )

When I try to unset an particular array element based on id, after unset i'm getting the array like below.

Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )

The array element is getting unset, but the next array element doesn't move to the deleted array position.

For unset an array element, I'm using the following code.

$i = 0;
foreach($cartdetails["products"] as $key => $item){
    if ($item['id'] == $id) {
        $match = true;
        break;
    }
    $i++;
}
if($match == 'true'){
    unset($cartdetails['products'][$i]);
}

How to solve this issue? Please kindly help me to solve it.

Thanks in advance.

Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.

$i = 0;
foreach($cartdetails["products"] as $key => $item){
    if ($item['id'] == $id) {
        $match = true;
        break;
    }
    $i++;
}
if($match == 'true'){
    unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);

Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.

http://www.php.net/manual/en/function.array-splice.php

http://php.net/manual/en/function.unset.php

Why don't you use this???

$id = 9;
foreach($cartdetails["products"] as $key => $item){
   if ($item['id'] == $id) {
       unset($cartdetails['products'][$key]);
       break;
   }    
 }

Why do you use $i++ to find an element to unset?

You can unset your element inside foreach loop:

foreach($cartdetails['products'] as $key => $item){
    if ($item['id'] == $id) {
        unset($cartdetails['products'][$key]);
        break;
    }
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);