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
A:
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.
chaos
2009-08-28 02:19:38
I mean the value that corresponds with the key. If the value is another level of array it will skip it and recurse inward until it finds something with a non-array value.
Stephen Belanger
2009-08-28 02:27:33
A:
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.
Sinan Ünür
2009-08-28 02:22:48
+1
A:
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')
);
strager
2009-08-28 02:28:24
Didn't quite work, but got me on the right track. I put together a function called remove_recursive() for removing array items, now I need to make the add_recursive() and change_recursive(). :)
Stephen Belanger
2009-08-29 06:52:18