views:

331

answers:

1

Possible Duplicate:
PHP: get keys of independent arrays

Hello.

I have a multi-dimensional array. I want a function that finds the position of the given array key (all my array keys are strings) and then returns the position of the key as an array.

E.g:

$arr = array
(
    'fruit' => array(
        'apples' => array(),
        'oranges' => array(),
        'bananas' => array()
    ),
    'vegetables' => array(
        'tomatoes' => array(),
        'carrots' => array(),
        'celery' => array(),
        'beets' => array
        (
            'bears' => array(),
            'battlestar-galactica' => array()
        ),
    ),
    'meat' => array(),
    'other' => array()
);

Now if I call the function like this:

theFunction('bears');

It should return:

array(1, 3, 0);

TIA!

+2  A: 
function array_tree_search_key($a, $subkey) {
   foreach (array_keys($a) as $i=>$k) {
      if ($k == $subkey) {
         return array($i);
      }
      elseif ($pos = array_tree_search_key($a[$k], $subkey)) {
         return array_merge(array($i), $pos);
      }
   }
}
mario
Thanks, works! But is it possible to only use the $subkey string as a param, and always use the same array? Can't seem to get that to work...