php 在 foreach 循环中取消设置数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2852344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:54:17  来源:igfitidea点击:

Unset array element inside a foreach loop

php

提问by Richard Knop

So here is my code:

所以这是我的代码:

<?php

$arr = array(array(2 => 5),
             array(3 => 4),
             array(7 => 10));

foreach ($arr as $v) {
    $k = key($v);
    if ($k > 5) {
        // unset this element from $arr array
    }
}

print_r($arr);

// now I would like to get the array without array(7 => 10) member

As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).

正如你所看到的,我从一个单键 => 值数组的数组开始,我遍历这个数组并获取当前元素的一个键(这是一个单项数组)。

I need to unset elements of the array with key higher than 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.

我需要取消设置键大于 5 的数组元素,我该怎么做?我可能还需要删除值小于 50 或任何其他条件的元素。基本上我需要能够获得当前数组项的键,它本身就是一个包含单个项的数组。

回答by sasa

foreach($arr as $k => $v) {
    if(key($v) > 5) {
        unset($arr[$k]);
    }
}

回答by Alexander Konstantinov

It issafe in PHP to remove elements from an array while iterating over it using foreach loop:

在PHP安全,而使用foreach循环在它迭代从数组中删除元素:

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

回答by Amber

Use key()to get the first key from the sub-array.

用于key()从子数组中获取第一个键。

foreach($arr as $k => $v) {
    if(key($v) > 5) {
        unset($arr[$k]);
    }
}

回答by Robert McBean

It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?

在遍历集合时添加或删除集合并不是真正安全的。将您想要的元素添加到第二个数组中,然后转储原始元素如何?

回答by Rabesh Lal Shrestha

To unset array element we Used unset() and php function like below:

要取消设置数组元素,我们使用了 unset() 和 php 函数,如下所示:

foreach($array as $key=>$value)
{
   if(key($value) > 5) 
   {
      unset($array[$key]);
   }
}