duangao8359 2013-06-19 08:45
浏览 37
已采纳

在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.

  • 写回答

4条回答 默认 最新

  • doujiexin1136 2013-06-19 08:50
    关注

    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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法