0

I have tried the following:

$tree['uid1']['page'] = "page1";
$tree['uid1']['childs']['uid2']['page'] = "page2";
$tree['uid1']['childs']['uid3']['page'] = "page3";

array_walk_recursive($tree, function (&$item, $key) {
  echo $key.', ';
  if ($key == 'uid3') {
    // push array('childs' => array('uid4' => array('page' => 'page4')))
  }
});

But echo $key.', '; only returns me the last key ("page") Have I done something wrong or have I misunderstood the function "array_walk_recursive"

rayphi
  • 503
  • 2
  • 14
  • 30

1 Answers1

2

If you take a look at the first comment at the documentation you will realice it doesn't work as you expected:

  • THIS FUNCTION ONLY VISITS LEAF NODES *

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function. The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray). This has the effect as to make this function unusable for most practical situations.

If you want to check whether a key exist in your array or not, you might want to take a look at this solutions.

Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336