Generating a JavaScript array from a PHP array

前端 未结 2 912
名媛妹妹
名媛妹妹 2020-12-04 00:14

Suppose that I have a string $var:

//php code

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

Now I get the array as

相关标签:
2条回答
  • 2020-12-04 00:29

    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);
    
    0 讨论(0)
  • 2020-12-04 00:33

    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 讨论(0)
提交回复
热议问题