Firs off, I am struggling to phrase the questions correctly... so bear with me. I am trying to modify the given array using a foreach loop that runs through each array key/value recursively. However, I do not want to replace a key or value, instead I need to add a new key and value to the same level as the matched key.
In the code below I walk through each key value in the array, and if a key and value match, I want to add a new key to that same level where the match occurred. I can find the match, but I don't know how to update the array. I would rather update the existing array than build a new one.
Here's what I am trying to accomplish
Given this array:
array(
array(
'name' => 'name',
'label' => 'Label'
),
array(
'name' => 'name',
'label' => 'Label',
'sub_fields' => array(
array(
'name' => 'my_desired_target',
'label' => 'Label'
)
)
)
);
function change_recursively($arr){
foreach($arr as $key => $val){
if(is_array($val)){
change_recursively($val);
}else{
if($key == 'name' && $val == 'my_desired_target'){
//How to add new key here?
$arr['new_key'] = 'my new value';
}
}
}
}
Below is the result I am looking for if I were to var_dump $arr. In this case the key 'name' and the value 'my_desired_target" were matched, and a new key 'new_key' and value 'my new value' were added to that same level.
array(
array(
'name' => 'name',
'label' => 'Label'
),
array(
'name' => 'name',
'label' => 'Label',
'sub_fields' => array(
array(
'name' => 'my_desired_target',
'label' => 'Label',
'new_key' => 'my new value'
)
)
)
)
I have looked into using array_walk_recursive, and array_map, but neither function seems to track how deep you are in the array.