JVK
JVK

Reputation: 3912

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?

Upvotes: 1

Views: 2514

Answers (2)

Wilon
Wilon

Reputation: 117

Can't do it with array_walk_recursive(). Documentation

Try this recursive function.

$fruits = array('sweet' => 'sugar', 'sour' => 'lemon', 'myfruits' => array('a' => 'apple', 'b' => 'banana'));

function test_alter(&$item1, $key){
  print $key;
  print "<br />";
  // recursive
  if (is_array($item1)) array_walk ($item1, 'test_alter');
}
array_walk ($fruits, 'test_alter');

Upvotes: 1

Jon
Jon

Reputation: 437376

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";
    }
}

Upvotes: 2

Related Questions