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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?