Question

I have an assoc. multidimensional array and a function:

// input:

$array = array();
$array['keyname0'] = array(
  'key0' => 'value0',
  'key1' => 'value1',
  //etc,
);
$array['keyname1'] = array(
  'key0' => 'value0',
  'key1' => 'value1',
  //etc,
);

// method:

function getCurrentParentArrayKey($array){
  //should return current key name of this array
  //I can't for the life of me find any array function on php.net or anywhere that solves this
}

// execute:

print getCurrentParentArrayKey($array['keyname0']);

// output:

keyname0

a better example might be:

$users=array(
  'michael' => array(
    'age' => '28',
    'height' => '5\'9"',
  )
);

function getUserName($array){
  //do something
  //@return: 'michael'
}

print getUserName($users['michael']);
Was it helpful?

Solution 2

You could add the parent key as a value of your array:

array(
    'key1' => array(
         'subkey1' => 'value1',
         'subkey2' => 'value2',
         'subkey3' => 'value3',
         'keyinparent' => 'key1'
    ),
    'key2' => array(
         'subkey4' => 'value4',
         'subkey5' => 'value5',
         'subkey6' => 'value6',
         'keyinparent' => 'key2'
    )
)

It requires processing before you pass the sub-array to the function though.

OTHER TIPS

Going on the super awesomely quick comments received i think i have 2 possible solutions...

(note: this is why it's called MVC not VMC or CVM lol)

example 1:

(add parent key name to child array):

$users=array(
  'michael' => array(
    'name' => 'michael', // add the parent arrays key name to the child array @see answer 2
    'age' => '28',
    'height' => '5\'9"',
  )
);

function getUserName($array){
  return $array['name'];
}

print getUserName($users['michael']); // 'michael'

example 2:

(pass whole array to function and pass key name as argument)

$users=array(
  'michael' => array(
    'age' => '28',
    'height' => '5\'9"',
  ),
  'adrienne' => array(
    'age' => '26',
    'height' => '5\'3"',
  )
);

function getName($array,$array_key){
    $keys = array_keys($array);
    $key = array_search($array_key, $keys);
    return $keys[$key];
}

print 'Name: '.getName($users,'michael');

but if your aware of the key name enough to provide it to the function getName() you could just provide the key name to the output...

$keyname = 'michael';
print 'name: '.$keyname;

I don't believe you're able to, when you are passing $array['keyname0'] to getCurrentParentArrayKey(), you lose context of the parent array since it is resolved to the inner array before it gets passed in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top