I have a recursive $data
structure that I need to modify. Each node considered an $item
should get a property with the value of $value
added. Things that I tried (and how they failed) are:
-
array_walk_recursive
: Visits only leaf nodes. - Stack/queue: I failed to modify the original structure but only altered the copies on the stack/queue.
- Loops: Without the stack/queue approach I would need to know the nesting level and write an awful lot of nested loops.
-
array_map
: I failed to write a proper recursive callback given that the value of$value
is not static but the result of previous code. So it must somehow get "into" the callback. Sinceuse
is only available to anonymous functions I did not manage to write a recursive one. - Loop and recursive function: This answer to a similar question failed for the same reason as the
array_map
approach.
My situation in code looks similar to this example:
<?php
$value = 'example';
$data = array(
'foo' => 'bar'
'items' => array(
array(
'foo' => 'bar',
'items' => array(
array('foo' => 'bar')
)
)
)
);
// do this recursively to every member of an 'items' property:
$item['baz'] = $value;
Can you think of a different approach or help me straighten out one of those that I failed at so far?
Update
Some code that I tried that did not work:
// Parse error: syntax error, unexpected 'use' (T_USE), expecting '{'
function do (&$item) use ($value) {
$item['baz'] = $value;
foreach ($item['items'] as $next) {
do($next);
}
}
// Undefined variable: value
function do (&$item) {
$item['baz'] = $value;
foreach ($item['items'] as $next) {
do($next);
}
}
foreach ($data['items'] as $item) {
do($item);
}
Works for now (I would prefer not having to pass the $value
parameter, though):
function do (&$item, $value) {
$item['baz'] = $value;
foreach ($item['items'] as &$next) {
do($next, $value);
}
}
foreach ($data['items'] as &$item) {
do($item, $value);
}