PHP我无法弄清楚如何找到当前父数组的数组键?

时间:2014-01-17 22:58:42

标签: php arrays multidimensional-array array-key

我有一个关联。多维数组和函数:

//输入:

$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']);

3 个答案:

答案 0 :(得分:1)

继续收到超级快速的评论,我认为我有两种可能的解决方案......

(注意:这就是为什么它被称为MVC而不是VMC或CVM lol)

示例1:

(将父键名添加到子数组):

$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'

示例2:

(将整个数组传递给函数并传递键名作为参数)

$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'
    )
)

在将子数组传递给函数之前,它需要进行处理。