开发者

Generating a JavaScript array from a PHP array

开发者 https://www.devze.com 2022-12-17 06:28 出处:网络
Suppose that I have a string $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\', respectivel

Suppose that I have a string $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.

I want to use this all value in javas开发者_高级运维cript in this:

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

How can I generate that JavaScript in PHP?


I would have thought json_encode would be the most reliable and simplest way.

E.g.

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


Karl B's answer is better - use that!

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):

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.

If you're determined to use explode, then you can use its other-half, implode like this in your output:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号