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?
$arr['hardcodedKeyName']before any check is done. You cannot be sure this key is present or not. You should recursively get through the last depth of array searching foridand change if present, then go to the beginning