更换多维数组中的某些项目 [英] Replace certain items within multidimensional array

查看:118
本文介绍了更换多维数组中的某些项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,可以在阵列数目深有各不相同,例如:

I have an array that can vary in how many arrays deep there are, for example:

        array(
              'one' => array(
                             array(
                                'something' => 'value'
                                ),
                             array(
                                'something2' => 'value2'
                                ),
                             'another' => 'anothervalue'
                             ),
              'two' =>  array(
                             array(
                                'something' => 'value'
                                ),
                             array(
                                'something2' => 'value2'
                                ),
                             'another' => 'anothervalue'
                             )
              )

现在,让我们说,我想用钥匙'东西'来代替一切。

Now, let's say I want to replace everything with the key 'something'.

请问我需要使用递归函数通过数组进行迭代?还是有更好的办法?

Would I need to use a recursive function to iterate through the array? or is there a better way?

感谢您!

推荐答案

在看一看<一个href=\"http://php.net/manual/en/function.array-walk-recursive.php\"><$c$c>array_walk_recursive.这可能是在这样的情况下,会非常方便。

Have a look at array_walk_recursive. It may be quite handy in a situation like this.

下面是一个使用array_walk_recursive一个例子:

Here's an example using array_walk_recursive:

$arr = array(
      'one' => array(
            array('something' => 'value'),
            array('something2' => 'value2'),
            'another' => 'anothervalue'
            ),
      'two' =>  array(
            array('something' => 'value'),
            array('something2' => 'value2'),
            'another' => 'anothervalue'
            )
       );

function update_something(&$item, $key)
{
    if($key == 'something')
        $item = 'newValue';
}

array_walk_recursive($arr, 'update_something');

如果一个类的内部使用的回调方法必须与功能以及添加对象。这是通过一个阵列来实现的:

If used inside a class the callback method have to add the object along with the function. This is achieved with an array:

array_walk_recursive($arr, array($this, 'update_something'));

这篇关于更换多维数组中的某些项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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