最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Generating a JavaScript array from a PHP array - Stack Overflow

programmeradmin3浏览0评论

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 javascript in this:

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

How can I generate that JavaScript in PHP?

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 javascript in this:

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

How can I generate that JavaScript in PHP?

Share Improve this question edited Jan 21, 2010 at 13:42 Dominic Rodger 99.8k36 gold badges202 silver badges216 bronze badges asked Jan 21, 2010 at 13:35 webkulwebkul 2,86410 gold badges49 silver badges61 bronze badges 4
  • Why on earth are you first loading values into vars in php and then overload them to javascript anyway? – Younes Commented Jan 21, 2010 at 13:37
  • var name = ($exp[0],$exp[1],$exp[2]); to be honest i don't know what you are asking, but this is what you do in your examples... – Younes Commented Jan 21, 2010 at 13:38
  • 1 @Younes: It is helpful, sometimes... If you wan't to show, for example, a variable that is stored in a session with Javascript without firing a ajax request after the page is loaded. – Harmen Commented Jan 21, 2010 at 13:41
  • @vipinsahu - could you take a moment to review Karl's answer, and accept it if it works for you - his is better than mine! – Dominic Rodger Commented Jan 21, 2010 at 14:56
Add a comment  | 

2 Answers 2

Reset to default 20

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)

  1. 暂无评论