Search code examples
phprecursionmultidimensional-arraykey

Add static prefix to values while recursively traversing a multidimensional array


I have the following code

$fruits = [
    'sweet' => 'sugar',
    'sour' => 'lemon',
    'myfruits' => [
        'a' => 'apple',
        'b' => 'banana'
    ]
];

function test_alter(&$item1, $key, $prefix){
    print $key;
    print "<br />";
    $item1 = "$key $prefix: $item1";
}


array_walk_recursive($fruits, 'test_alter', 'fruit');

When I execute it, I get this

sweet<br />sour<br />a<br />b<br />

But the expected output is

sweet<br />sour<br />myfruits<br />a<br />b<br />

So how do I get myfruits printed there?


Solution

  • You can't with array_walk_recursive. You will need to use plain array_walk and provide the recursion yourself:

    function test_alter(&$item1, $key, $prefix) {
        print $key;
        print "<br />";
        if(is_array($item1)) {
            array_walk($item1, 'test_alter', $prefix);
        }
        else {
            $item1 = "$key $prefix: $item1";
        }
    }