Find array key in php and change its value or contents?

天涯浪子 提交于 2020-01-15 09:56:31

问题


Given a multi-dimensional array that you don't necessarily know the structure of; how would one search for a key by name and change or add to it's contents? The value of the key could be either a string or an array and the effects should be applied either way--I had looked at array_walk_recursive, but it ignores anything that contains another array...


回答1:


Does this work?

function arrayWalkFullRecursive(&$array, $callback, $userdata = NULL) {
    call_user_func($callback, $value, $key, $userdata);

    if(!is_array($array)) {
        return false;
    }

    foreach($array as $key => &$value) {
        arrayWalkFullRecursive($value);
    }

    return true;
}

arrayWalkFullRecursive($array,
    create_function(                // wtb PHP 5.3
        '&$value, $key, $data',
        'if($key == $data['key']) {
             $value = $data['value'];
         }'
    ),
    array('key' => 'foo', 'value' => 'bar')
);



回答2:


Array keys in PHP are ints and strings. You can't have an array array key. So yeah, array_walk_recursive() is what you want.




回答3:


From Arrays:

A key may be either an integer or a string.

Arrays cannot be used as keys.

To get the keys of an array, use array_keys.



来源:https://stackoverflow.com/questions/1344698/find-array-key-in-php-and-change-its-value-or-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!