I am trying to write a snippet that takes an multidimensional array and inserts some keys at the same level where a named search key is found. I don't have to rely on the structure of the array (but will be at most 5 levels) I can't use passing by reference so a traditional recurring function won't help with that approach.
I have 2 options: SPL or a recursion that re-constructs the array and alters it along the way
with SPL I can't seem to Insert a new value..
$a= new \ArrayObject($priceConfig);
$array = new \RecursiveArrayIterator($a);
$iterator = new \RecursiveIteratorIterator($array, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (is_array($value) && $key == 'prices') {
$iterator->offsetSet('myPrice',['amount'=>'1.00']);
}
}
print_r($a->getArrayCopy());
It won't insert the new key at the desired level but it does loop through the array.. what am I missing?
The recursive function that reconstructs the array and insert new values at my key search in the nested array works, but I would like to use the Iterators to do that..
function recursive( $input, $searchKey, $key=null) {
$holder = array();
if(is_array( $input)) {
foreach( $input as $key => $el) {
if (is_array($el)) {
$holder[$key] = recursive($el, $searchKey, $key);
if ($key == $searchKey) {
$holder[$key]['inertedPrice'] = "value";
}
} else {
$holder[$key] = $el;
}
}
}
return $holder;
}
INPUT (will always have some "prices key and structure at X level")
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
)
[key] => value
)
)
)
Output
[1] => Array
(
[1] => Array
(
[prices] => Array
(
[onePrice] => Array( [amount] => 10)
[finalPrice] => Array ([amount] => 10)
[INSERTEDPrice] => Array([amount] => value)
)
[key1] => value2
[key2] => value2
)
[2] => Array
(
[prices] => Array
(
[otherPrice] => Array([amount] => 20)
[finalPrice] => Array([amount] => 20)
[INSERTEDPrice] => Array([amount] => )
)
[key] => value
)
)
)