简体   繁体   中英

Most Efficient Way to Delete Nested Array Element

Say I have the following:

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

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

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

)

I want to delete the item with id = 5. I know I can loop through the array and unset, but I'm hoping for a more direct/efficient solution.

If you cannot make the IDs the keys of the outer array (then you could simply use unset($arr[5]); ), looping over the array is indeed the way to dg.

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

Another option would be using array_filter - that's less efficient though since it creates a new array:

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

Why don't you create the array with the keys set as the ID's? Eg:

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

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

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

)

You can then write:

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

For Multi level nested array

<?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;
    }
?>

The most efficient way would be to have 2 arrays.

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

Search for ID in your ID => Index helper array and the value will be the Index for your main array, then unset them both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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