views:

151

answers:

2

I have already posted a similiar question to this one some time ago, but now it's different, so please don't close this as a duplicate.

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 in the array, AS an array.

Here's an example array:

$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()
);

The function should have a variable/dynamic number of arguments (i.e. optional arguments). The arguments represent the "levels" (dimensions) of my array(s).

If the function gets called with one argument, the function should only look for keys on the first level/dimension of the array (i.e. in the example those would be 'fruit', 'vegetables', 'meat' and 'other').
If it gets called with two arguments, e.g. theFunction('vegetables', 'beets'), it should look for a key called 'vegetables' and then look for a "sub"key called 'beets' (ONLY in the 'vegetables' level/branch/dimension though!) In that example it would return array(1, 3).

Of course this should work with any number of levels/dimensions.

I hope this is clear enough, any help is GREATLY appreciated!

TIA!

A: 
function find($arr, $k1, $k2=null){
    if(!array_key_exists($k1, $arr)) //array level one only
        if(array_key_exists($k1, $arr))
            ;
        else
            ;
    else if(array_key_exists($k2, $arr[$k1]))
        ;
    else
        ;
 }
FallingBullets
A: 

I see that this Question has not had any love for some time, so I'll give it a swing.

function findKey( $srcArray , $fndArray , $depth=0 ){
  if( ( $keyIndex[] = array_search( $fndArray[$depth] , array_keys( $srcArray ) ) )!==false ){
    if( is_array( $srcArray[$fndArray[$depth]] ) )
      $nextLevel = findKey( $srcArray[$fndArray[$depth]] , $fndArray , $depth+1 );
    if( $nextLevel===false )
      return $keyIndex;
    return array_merge( $keyIndex , $nextLevel );
  }
  return false;
}

This function does return an array of array( 1 , 3 ) using the provided test data. It will provide the matched array, as far down as the match goes (ie if it can match the first 2 items out of 3, the returned array will have the numbers for the first 2).

Lucanos