简体   繁体   English

语言PHP数组-传递给Javascript的优雅方法

[英]Language PHP array - elegant way to pass to Javascript

I have a database with strings and which language this string belongs. 我有一个包含字符串的数据库,该字符串属于哪种语言。 A string has a unique name, which I use to identify it, and then a translation for each language. 字符串有一个唯一的名称(我用它来识别它),然后是每种语言的翻译。

With PHP, I get this information from the database and store it in an associative array like: 使用PHP,我可以从数据库中获取此信息,并将其存储在一个关联数组中,例如:

$languages['strings']['lang']['unique_string_name'] = $translation;

Now, as I want my Javascript code to be translated too, I need to pass it to. 现在,由于我也希望翻译Javascript代码,因此需要将其传递给。 I've tried doing it in JSON, but some $translation have quotes and double quotes, and it's a hell to escape and get it all correct - because escaping just escapes the whole JSON string, not only translation. 我试过用JSON进行操作,但是有些$ translation有引号和双引号,这真是一个令人难以理解的转义,因为转义仅转义了整个JSON字符串,而不仅仅是转义。

So, what I've done is loop the whole array and echoing the $translation in a Javascript associative array again, but this time with addslashes - only the translation. 因此,我要做的是循环遍历整个数组,并再次在Javascript关联数组中回显$ translation,但这一次加了斜杠-仅包含翻译。

However, if I look to the Source Code, I see 600 lines of Javascripts entries, one for each translation (of course, this has nothing strange, just simply UGLY). 但是,如果我查看源代码,则会看到600行Javascripts条目,每个翻译条目一个(当然,这并不奇怪,只是丑陋)。

I was wondering if there's a much cleaner way of passing this translation array to my Javascript code without having to loop the PHP array and echo it to a JS variable. 我想知道是否有一种更干净的方法将此传递数组传递给我的Javascript代码,而不必循环PHP数组并将其回显到JS变量。

Thanks for your time and answers! 感谢您的时间和答复!

All you really need is: 您真正需要的是:

<script type="text/javascript">
var languages = <?php echo json_encode($languages); ?>;
</script>

You'll end up with an exact duplicate of your PHP array in JS, so 您最终将得到与JS中的PHP数组完全相同的副本,因此

echo $languages['strings']['lang']['unique_string_name']; // PHP
alert(languages.strings.lang.unique_string_name); // JS

will both bring up the same translation. 都将带来相同的翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM