繁体   English   中英

删除嵌套数组元素的最有效方法

[英]Most Efficient Way to Delete Nested Array Element

说我有以下几点:

Array(
[0] => Array
    (
        [id] => 1
        [item] => first item
    )

[1] => Array
    (
        [id] => 3
        [item] => second item
    )

[2] => Array
    (
        [id] => 5
        [item] => third item
    )

)

我想删除id = 5的项目。我知道我可以遍历数组并取消设置,但是我希望有一个更直接/有效的解决方案。

如果不能将ID用作外部数组的键(那么您可以简单地使用unset($arr[5]); ),则遍历数组确实是dg的方法。

foreach($arr as $key => $value) {
    if($value['id'] === 5) {
        unset($arr[$key]);
        break;
    }
}

另一个选择是使用array_filter效率较低,因为它创建了一个新数组:

$arr = array_filter($arr, function($value) {
    return $value['id'] !== 5;
});

为什么不使用设置为ID的键来创建数组? 例如:

Array(
[1] => Array
    (
        [id] => 1
        [item] => first item
    )

[3] => Array
    (
        [id] => 3
        [item] => second item
    )

[5] => Array
    (
        [id] => 5
        [item] => third item
    )

)

然后,您可以编写:

<?php    
unset($array[5]); // Delete ID5
?>

对于多层嵌套数组

<?php
    function remove_array_by_key($key,$nestedArray){
        foreach($nestedArray as $k=>$v){
            if(is_array($v)){
                remove_array_by_key($key,$v);
            } elseif($k==$key){
                unset($nesterArray[$k]);
            }
        }
        return $nestedArrat;
    }
?>

最有效的方法是拥有2个阵列。

ID => Index
Index => Object (your current array)

在您的ID => Index helper数组中搜索ID,该值将成为您的主数组的Index,然后同时取消设置它们。

暂无
暂无

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

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