I have a multidimensional array as per below example which I want to search through for a specific value $needle. If this value is found I want to add a new key=> value pair for each node of the array branch where the $needle is subsequently found. The needle should be unique but the depth of the sub arrays is dynamic. Example:
$data= [
0=> [
'title' => 'alpha',
'children' => [],
],
1 =>[
'title' => 'beta',
'children' => [
0=>[
'title' => 'charlie',
'children' => [],
],
1=>[
'title' => 'delta',
'children' => [],
],
2=>[
'title' => 'echo',
'children' => [
0=>[
'title' => 'foxtrot',
'children' => [],
],
],
],
],
],
2 => [
'title' => 'gulf',
'children' => []
]
Now when I search for $needle= foxtrot I want to add to each of the subarrays "active" => 1 e.:
$data= [
0=> ...
1 =>[
'title' => 'beta',
**'active' => 1,**
'children' => [
0=>[
'title' => 'charlie',
'children' => [],
],
1=>[
'title' => 'delta',
'children' => [],
],
2=>[
'title' => 'echo',
**'active' => 1,**
'children' => [
0=>[
'title' => 'foxtrot',
**'active' => 1,**
'children' => [],
],
],
],
],
],
My not working attempt. I don't know how I correctly merge the key => value on each finding:
function array_mod_active($array, $needle, $parent_key='' )
{
foreach($array as $key => $value) {
if (is_array($value)) {
array_mod_active($value, $needle, $key );
} elseif ($value === $needle) {
array_merge(array('active' => 1), $array[$parent_key]);
}
}
return $array;
}