如何从PHP中的多维数组中检索值

时间:2015-12-01 01:49:08

标签: php

在PHP中如何将标识符传递给函数以从多维数组中检索值?使用以下功能,如何使用$ identifier变量返回' Female'

function phrase($identifier) {
  $lang = array();
  $lang['settings']    = 'Personal settings';
  $lang['entergender'] = 'Please select your gender';
  $lang['gender']['m'] = 'Male';
  $lang['gender']['f'] = 'Female';

  return $lang[$identifier];
}

phrase('gender/f');//obviously this won't work

1 个答案:

答案 0 :(得分:1)

您可以在多个数组维度中编写variadic function来请求。然后,您将使用每个维度的键作为参数调用您的函数。

下面的代码使用func_num_args()func_get_arg()来迭代传递给函数的参数。

function phrase() {
  $lang = array();
  $lang['settings']    = 'Personal settings';
  $lang['entergender'] = 'Please select your gender';
  $lang['gender']['m'] = 'Male';
  $lang['gender']['f'] = 'Female';
  $lang['foo']['bar']['baz'] = 'Hello!';

  $val = $lang;
  for ($i = 0; $i < func_num_args(); $i++) {
    $val = $val[func_get_arg($i)];
  }

  return $val;
}

print phrase('settings');
print phrase('gender', 'f');
print phrase('foo', 'bar', 'baz');