Reputation: 2783
$allVal = array(array(123, 0), array(345, 1), array(456, 2));
Code at above is an PHP array, currently I would like to pass this array to javascript and the output in Javascript should look like the following:
<script type="text/javascript">
var d = [[123, 0], [345, 1], [456, 2]];
</script>
BTW: PHP code and Js code in the same page.
Is there anyone can help me? Thanks in advance!
Upvotes: 0
Views: 128
Reputation: 2359
You can use php's json_encode method to convert an array into a javascript oject prior to sending it back to the client side. See
http://php.net/manual/en/function.json-encode.php
--Inline Use a line similar to
<?php echo "var = ". json_encode($myArray); ?>
--Asynchronous A line similar to
<?php echo json_encode($myArray); ?>
One thing you will have to take into consideration is that you'll need to pass a header to the server stating that you expect the response format to be json.
Upvotes: 1
Reputation: 27313
json_encode
should be able to help you
<?php
$allVal = array(array(123, 0), array(345, 1), array(456, 2));
?>
<script type="text/javascript">
<?php echo 'var d = ' . json_encode($allVal) . ';'; ?>
</script>
Upvotes: 8