Home » Php » Changing specific keys in multidimensional array with unknown depth in php

Changing specific keys in multidimensional array with unknown depth in php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I would like to prepend “Hello ” to value of an item if key is “photo” or “image”; I could simply accomplish it thanks to multiple foreach loops if array’s depth was known but here the depth is unknown.

$array = [
 array("sth1" => "val", "sth2" => "val", "sth3" => array("sth" => array( ... ), "photo" => "val")),
 array("img" => "val", "sth" => "val"),
];

What I have tried so far but does not visit all nodes:

function chkData(&$item, $key){
    $media = ['photo', 'img'];
    if(in_array($key, $media)){
        $item = 'Hello ' . $item;
    }
}

array_walk_recursive($array, 'chkData'); // callback function does not visit every node

Update:
RecursiveIteratorIterator was a good choice, It could return all the keys I needed. The problem is that I can not change the value:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
    $value = 'Hello ' . $value; // does not work
}
How to&Answers: