简体   繁体   English

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

[英]After deleting the particular multidimensional array element in PHP, the Next array elements are not positioning automatically

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. 当我尝试根据id取消设置特定的数组元素时,取消设置后,我得到的数组如下所示。

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. 好吧,如果您想保持顺序,而只想重新索引键,则可以使用array_values()函数。

$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. 使用unset不会改变数组的索引。 You probably want to use array_splice. 您可能要使用array_splice。

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

http://php.net/manual/en/function.unset.php http://php.net/manual/zh/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? 为什么使用$ i ++查找要取消设置的元素?

You can unset your element inside foreach loop: 您可以在foreach循环中取消设置元素:

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']);

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

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