簡體   English   中英

如何從JavaScript獲取所有PHP數組索引?

[英]How to get all php array index from javascript?

我有一個php文件,在其中保存了所有語言字符串。 這是內容:

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

本質上,當我加載一個javascript文件時,我想將所有數組索引存儲在這樣的變量中:

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

此代碼行插入到腳本中,該腳本在php文件中可用。 現在,在執行此行之前,我已經導入了所有字符串翻譯都可用的php文件。 我想要實現的是在變量Lang獲得該數組的所有索引。 實際上,我可以像這樣從php加載單個字符串轉換:

lang('step_one');

但是如何將這個數組保存在javascript變量中?

您可以使用array_keys檢索所有陣列鍵。 為此,您需要您的函數根據要求返回整個數組。 你可以做到這一點與離開參數( $phrase )空,如果有狀況做一個emptylang功能。 您還需要在函數中設置$phrase的默認值, $phrase在不將參數傳遞給函數時不引發任何錯誤。

echo json_encode(array_keys(lang());

和功能:

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

我還添加了isset ,以確保所請求的元素存在於您的語言數組中。 這將防止發出警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM