How to change the value of an element with array_walk?
multidimensional-array, php
Solution
You may achieve that with recursive call of your callback function. I've implemented sample with closure, like:
//replacement array:
$replace = [
'1' => 'foo',
'2' => 'bar',
'5' => 'baz'
];
array_walk($items, $f=function(&$value, $key) use (&$f, $replace)
{
if(isset($replace[$value['id']]))
{
$value['title'] = $replace[$value['id']];
}
if(isset($value['children']))
{
//the loop which is failing in question:
foreach($value['children'] as $k=>&$child)
{
$f($child, $k);
}
//Proper usage would be - to take advantage of $f
//array_walk($value['children'], $f);
}
});
As you can see - all that you need is to pass value by reference and iterate it inside callback as a reference for `foreach` too.
Problem
How can I change the value of an element with array_walk? For instance, this is my array, ``` $items = array( 0 => array( "id" => "1", "title" => "parent 1", "children" => array() ), 1 => array( "id" => "2", "title" => "parent 2", "children" => array ( 0 => array( "id" => "4", "title" => "children 1" ), 1 => array( "id" => "5", "title" => "children 2" ) ), ) ); ``` And I can change it with this below, ``` function myfunction(&$item,$key) { if($item['id'] === '1') { $item['title'] = 'hello world en'; } } array_walk($items,"myfunction"); print_r($items); ``` But I have a nested children and I want to change the value in that too, and I will get error if I do this, ``` function myfunction(&$item,$key) { if($item['id'] === '1') { $item['title'] = 'hello world en'; } if($item['id'] === '4') { $item['title'] = 'hello world en'; } foreach($item as $key => $value) { if(is_array($value)) { myfunction($value,$key); } } } ``` error, Notice: Undefined index: id in ...index.php on line xx Any idea what should I do if there is a nested children in an array?