简体   繁体   中英

Assigning a php array into a javascript array

I am trying to assign a PHP array into a javascript variable like this:

var jsArray = <?php echo $phpArray; ?>;

But it doesn't work.
What am I doing wrong?

You should try to use JSON

var jsArray = <?php echo json_encode($phpArray); ?>;

accessible then via

jsArray.someKey

demo

you can serialize array in php using json_encode and use it inside JS

http://php.net/manual/en/function.json-encode.php

<?php
$series = array("name"=>"N51",
                "data"=>array(1024,
                              array("y"=>2048,
                                    "events"=>array("mouseOver"=>'function(){$reporting.html(\'description of value\');}')
                                   ),
                              4096)
               );
json_encode($series);
?>

The above code outputs:

{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":"function(){$reporting.html('description of value');}"}},4096]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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