如何使用array_walk_recursive取消设置元素 [英] How to unset elements using array_walk_recursive

查看:130
本文介绍了如何使用array_walk_recursive取消设置元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数组未设置元素嵌套到另一个数组中,只有第一个 N 元素将被保留( N A途径是predefined)。只有具有数字索引元素都应该受到影响。

I need to unset elements from arrays that are nested into another array, in a way that only the first N elements would be kept (N being predefined). Only elements that have a numerical index should be affected.

输入数组:

Array
(
    [0] => Array (
        [a] => 'w'
        [b] => Array (
             [0]=> 'x'
             [1]=> 'x'
             [2]=> 'x'
        )
    )               
    [1] => Array (
        [a] => 'y'
    )
    [2] => Array (
        [0] => 'z'
        [1] => 'z'
        [2] => 'z'
    )
)

所需的输出(带有 N = 2

Array
(
    [0] => Array (
        [a] => 'w'
        [b] => Array (
             [0]=> 'x'
             [1]=> 'x'
        )
    )               
    [1] => Array (
        [a] => 'y'
    )
)

根据上述定义

,仅 [0] [B] [2] [2] 得到未设置的,因为他们有一个数字指标,因为它们都重新presnted各自阵列的第三元素。

Based on the above definition, only [0][b][2] and [2] got unset because they had a numerical index and because they both represnted the 3rd element of their respective array.

推荐答案

没有测试过,但是这样的事情可能会奏效。

Haven't tested but something like this might work.

function myFunc(&$array){
foreach($array as $key=>&$value){
 if(is_array($value)){
   myFunc($value);
 }
 if(is_numeric($key) && $key > 1){
   unset($array[$key]);
 }
}
}

关于array_walk。 php.net说:

About array_walk. php.net says:

程序员不能添加,设置或
  重新排序的元素。如果回调不
  不尊重这一要求,
  此函数的行为是
  不确定的,和未predictable。

the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

这篇关于如何使用array_walk_recursive取消设置元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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