简体   繁体   English

如何在PHP的array_walk_recursive函数中为特定键创建异常?

[英]How can I create an exception for a particular key in PHP's array_walk_recursive function?

I have a multidimensional associative array, and I want to apply array_walk_recursive so that I can execute a function on every single value. 我有一个多维关联数组,我想应用array_walk_recursive,以便我可以对每个值执行一个函数。

However, whenever a key is named "special" I want to execute a different function. 但是,每当一个键被命名为“特殊”时,我想执行一个不同的功能。

So if the array is like this: 所以如果数组是这样的:

$array = array('a' => 'apple', 'b' => 'banana', 'special' => 'xylophone', 'c' => 'cherry');

Then I want to execute function doThis() on 'a', 'b', and 'c', and I want to execute doThat() on 'special'. 然后我想在'a','b'和'c'上执行函数doThis(),我想在'special'上执行doThat()。

Is this possible? 这可能吗?

(Note: my example is a simple array, but the real code needs to act on multidimensional array) (注意:我的例子是一个简单的数组,但真正的代码需要作用于多维数组)

Your function gets passed the key as the second argument: 您的函数作为第二个参数传递给键:

function foo(&$item, $key) {
    if ($key == 'special') {
        return doThat($item, $key);
    }
    return doThis($item, $key);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM