简体   繁体   中英

Double dimensional array value from PHP

I have a PHP file that is going to write a two-dimensional array in JavaScript:

<?php
    print "<script language='javascript'>";
    print " extra[0][0] = new Array(1,'Bob',12);";
    print " extra[0][1] = new Array(2,'Alice',18);";
      ..
    // Need to assign the extra[1][0], extra[1][1] and so on.
    print "</script>";
 ?>

Mu.js:

  var extra =  new Array();
  ...

How do I assign the two-dimensional array from PHP to a JavaScript variable?

json_encode is your friend: json_encode in the PHP manual


<script type="text/javascript">
  var jsArray = <?= json_encode($my_array) ?>;
</script>

Yes, wvanbergen is right, json_encode is your friend. You can create the array as JSON:

<?php
    $extra = array(
      array(1,'Bob',12),
      array(2,'Alice',18)
      );

    echo "var extra = " . json_encode($extra) . ";";
?>

And in your javascript it will output:

var extra = [[1,"Bob",12],[2,"Alice",18]];
<script type="text/javascript">
 var jsArray = <?php json_encode($my_array); ?>;
</script>

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