我有一个关联。多维数组和函数:
//输入:
$array = array();
$array['keyname0'] = array(
'key0' => 'value0',
'key1' => 'value1',
//etc,
);
$array['keyname1'] = array(
'key0' => 'value0',
'key1' => 'value1',
//etc,
);
//方法:
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
}
//执行:
print getCurrentParentArrayKey($array['keyname0']);
//输出:
keyname0
更好的例子可能是:
$users=array(
'michael' => array(
'age' => '28',
'height' => '5\'9"',
)
);
function getUserName($array){
//do something
//@return: 'michael'
}
print getUserName($users['michael']);
答案 0 :(得分:1)
继续收到超级快速的评论,我认为我有两种可能的解决方案......
(注意:这就是为什么它被称为MVC而不是VMC或CVM lol)
$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'
$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');
但是如果你知道足够的密钥名称将它提供给函数getName(),你可以只为输出提供密钥名称......
$keyname = 'michael';
print 'name: '.$keyname;
答案 1 :(得分:0)
我不相信你能够,当你将$ array ['keyname0']传递给getCurrentParentArrayKey()时,你丢失了父数组的上下文,因为它在传入之前被解析为内部数组。
答案 2 :(得分:0)
您可以将父键添加为数组的值:
array(
'key1' => array(
'subkey1' => 'value1',
'subkey2' => 'value2',
'subkey3' => 'value3',
'keyinparent' => 'key1'
),
'key2' => array(
'subkey4' => 'value4',
'subkey5' => 'value5',
'subkey6' => 'value6',
'keyinparent' => 'key2'
)
)
在将子数组传递给函数之前,它需要进行处理。