简体   繁体   English

从PHP数组生成JavaScript数组

[英]Generating a JavaScript array from a PHP array

Suppose that I have a string $var : 假设我有一个字符串$var

//php code

$var = "hello,world,test";
$exp = explode(",",$var);

Now I get the array as exp[0],exp[1],exp[1] as 'hello' , 'world' and 'test' , respectively. 现在我将数组分别作为exp[0],exp[1],exp[1]作为'hello''world''test'

I want to use this all value in javascript in this: 我想在javascript中使用这个全部值:

var name = ['hello','world','test'];

How can I generate that JavaScript in PHP? 如何在PHP中生成JavaScript?

I would have thought json_encode would be the most reliable and simplest way. 我原以为json_encode是最可靠和最简单的方法。

Eg 例如

$var = "hello,world,test";
$exp = explode(",",$var);
print json_encode($exp);

Karl B's answer is better - use that! 卡尔B的答案更好 - 使用它!

Wouldn't an easier way be like this: 不是一个更容易的方式是这样的:

$var = "hello,world,test";
$var = str_replace(",", "','", $var);

Then wherever you're spitting out JavaScript (assuming you can use PHP there): 然后,无论你在哪里吐出JavaScript(假设你可以在那里使用PHP):

var name = ['<?php echo $var; ?>'];

This doesn't deal properly with quoted values though - if you want that, you're better off with using fgetscsv et al. 但这并没有适当地处理引用的值 - 如果你想要,你最好使用fgetscsv等。

If you're determined to use explode , then you can use its other-half, implode like this in your output: 如果你决定使用explode ,那么你可以在输出中使用它的另一半,内implode这样的内容:

var name = ['<? php echo implode("','", $var); ?>'];

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

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