tags:

views:

115

answers:

5

I'm now implement such a task:I need to convert PHP variables to javascript

$arr['name1'] = 'value1';
$arr['name2'] = 'value2';

so that after processing,should be:

<script type="text/javascript">
var name1 = 'value1';
var name2 = 'value2';
...

I hoped to do it this way:

<script>
list(<?php echo join(',',array_keys($arr)?>) = <?php echo json_encode(array_values($arr));?>
+1  A: 

Nope, sorry.

You might instead consider simply using json_encode to print the object to the script.

<?php
    $a = array('foo' => 'bar');
    json_encode($a); // returns {"foo":"bar"} which is valid Javascript syntax
?>

<script>var obj = <?php echo json_encode($a); ?></script>
Matchu
A: 

You could use json.

var arr = { "name1" : "value1", "name2": "value2"}

Then to get a value you just access it like a field

var firstVal = arr.name1
TwentyMiles
I need a variable called `name1`,and its value should be `value1`.Not `firstval`
Just get creative, silly. If you want the variable to be named something else, change the name.
Matchu
A: 

Hi, you might want to have a look at PHP JS, it will help you in your conversion tasks. Thanks

Sarfraz
List is more of a language construct; PHP JS doesn't seem to have implemented it, from what I can find.
Matchu
+2  A: 

Check php.js, they have ported a lot of features of PHP to JS, list() is listed as experimental.

Alix Axel
List is more of a language construct; PHP JS doesn't seem to have implemented it, from what I can find.
Matchu
Two down-votes for a legitimate suggestion... All right.
Alix Axel
@Matchu: I know it's a language construct, I didn't say otherwise. I've provided a link to the php.js experimental port of `list()`.
Alix Axel
Oh, wow. Was that there before? I totally missed it. Give the post a token edit and I'll switch to upvote :)
Matchu
@Matchu: Just did, if you upvote me I won't win any rep points as I'm already capped for today - but it can reflect the possible usefulness of the answer. =)
Alix Axel
+1  A: 

Probably misunderstood the question, but wouldn't this work?

echo "<script>";
foreach ($arr as $k => $v) 
{
    echo "var $k = $v;";
}
echo "</script>";
Per Holmäng
Yes,that's almost what I mean.But I'm just not sure if there is a more concise solution like `list`?
Not built into Javascript. You'd have to use a custom function for that, which would be pretty silly when you can just use an extremely simple loop - not to mention that the loop would be far more readable to other developers.
Matchu
If I'm not counting wrongly,you've mentioned silly 2times.You can go away!I don't need your help at all!
@unknown But it is silly. Just like with your last question, you are creating problems where there are none. Just write the variables in JSON or use `foreach`. What is so much more concise about `list`?
Gordon