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.

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作