在foreach循环中未设置数组元素 [英] Unset array element inside a foreach loop

查看:184
本文介绍了在foreach循环中未设置数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<?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).

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

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.

推荐答案

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

这篇关于在foreach循环中未设置数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆