views:

1095

answers:

2

Dear All

I have a PHP file 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] so on.
      print "</script>";    

 ?>

Mu.js:

  var extra=new Array();
  ...

Any suggestion to assign the two-dimensional array from PHP to a javascript variable?

+7  A: 

json_encode is your friend: json_encode in the PHP manual


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

wvanbergen
I have encoded in PHP, I unable to decode in javascript ,could u please suggest an example?
venkatachalam
Just build the array in PHP as you want it to look in Javascript, and then pass that array to json_encode.
wvanbergen
A: 
<script type="text/javascript">
 var jsArray = <?php json_encode($my_array); ?>;
</script>
venkatachalam