简体   繁体   中英

How to retrieve value from multi-dimenionsal array in PHP

In PHP how can I pass on an identifier to a function to retrieve a value from a multi-dimensional array? With the below function, how can I return 'Female', using the $identifier variable?

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

You could write a variadic function to request in multiple array dimensions. You would then call your function with each dimension's key as an argument.

The code below uses func_num_args() and func_get_arg() to iterate over the arguments passed to the function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM