开发者

Removing a value from a PHP Array

开发者 https://www.devze.com 2023-04-02 10:46 出处:网络
Using PHP I\'m trying to remove an element from an array based on the value of the element. For example with the following array:

Using PHP I'm trying to remove an element from an array based on the value of the element.

For example with the following array:

Arra开发者_开发技巧y
(
    [671] => Array
        (
            [0] => 1
            [1] => 100
            [2] => 1000
        )
    [900] => Array
        (
            [0] => 15
            [1] => 88
        }
)

I'd like to be able to specify a value of on of the inner arrays to remove. For example if I specified 100 the resulting array would look like:

Array
(
    [671] => Array
        (
            [0] => 1
            [2] => 1000
        )
    [900] => Array
        (
            [0] => 15
            [1] => 88
        }
)

My first thought was to loop through the array using foreach and unset the "offending" value when I found it, but that doesn't seem to reference the original array, just the loop variables that were created.

Thanks.


foreach($array as $id => $data){
    foreach($data as $index => $offending_val){
         if($offending_val === 100){
            unset($array[$id][$index]);
         }
    }
}


You can use:

array_walk($your_array, function(&$sub, $key, $remove_value) {
    $sub = array_diff($sub, array($remove_value));
}, 100);


Couple of ideas:

You could try array_filter, passing in a callback function that returns false if the value is the one you want to unset. Using your example above:

$new_inner_array = array_filter($inner_array, $callback_that_returns_false_if_value_100)

If you want to do something more elaborate, you could explore the ArrayIterator class of the SPL, specifically the offsetUnset() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消