CodeIgniter3扩展语言助手

时间:2018-02-19 12:47:56

标签: php arrays codeigniter codeigniter-3

我正在使用CodeIgniter 3,我想扩展默认语言助手。

默认情况下,CodeIgniter允许函数lang(language_key)从语言文件中获取值,但我的语言文件不同。

默认语言文件:

$lang = [
    'MONTH_JANUARY' => 'January',
    'MONTH_FEBRUARY' => 'February',
];

我的档案:

$lang = [
    'MONTH' => [
        'JANUARY' => 'January',
        'FEBRUARY' => 'February',
    ],
];

我想用爆炸创建一个辅助函数。

例如,使用lang('MONTH.JANUARY')它会查找$ lang ['MONTH'] ['JANUARY']并返回'January'。

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

使用引用遍历数组

function lang($string) {
  $lang = [
    'MONTH' => [
        'JANUARY' => 'January',
        'FEBRUARY' => 'February',
    ],
  ];

  $p = &$lang;
  foreach(explode('.', $string) as $x) {
     if(! isset($p[$x])) {
       // key does not exist - do something
     }
     else {
       $p = &$p[$x];
     }   
  }
  return $p;
}


echo lang('MONTH.JANUARY'); // 'January'

demo