dqxuiq7772 2016-01-27 15:33
浏览 42
已采纳

如何从JavaScript获取所有的PHP数组索引?

I have a php file where I saved all language string. This is the content:

function lang($phrase)
{
    static $lang = array(
        'step_one' => 'First step',
        'step_two' => 'Second step',
         ... and so on ...
    );
    return $lang[$phrase];
}

Essentially, when I load a javascript file I want store all array index in a variable like this:

var Lang = <?php echo json_encode(lang()); ?>;

this code line is inserted in a script, this script is available in a php file. Now before of execute this line I have imported the php file where all string translation is available. What I'm trying to achieve, is get all index of this array, in the variable Lang. Actually I can load a single string traduction from php like this:

lang('step_one');

but how I can save this array in javascript variable?

  • 写回答

1条回答 默认 最新

  • duanfu9523 2016-01-27 15:47
    关注

    You can use array_keys to retrieve all array keys. To do that you need your function to return the whole array on request. You can do that with leaving the argument ($phrase) empty and do an if condition with empty in your lang function. You also need to set a default value for $phrase in your function to not raise any errors if you don't pass an argument to the function.

    echo json_encode(array_keys(lang());
    

    And the function:

    function lang($phrase = "")
    {
        static $lang = array(
            'step_one' => 'First step',
            'step_two' => 'Second step',
             ... and so on ...
        );
    
        if(empty($phrase)) {
            return $lang;
        } else {
            if(isset($lang[$phrase])) { //isset to make sure the requested string exists in the array, if it doesn't - return empty string (you can return anything else if you want
                return $lang[$phrase];
            } else {
                return '';
            }
        }
    }
    

    I also added isset to make sure the requested element exists in your language array. This will prevent raising warnings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能