How to make a java script array from php array?

user1029108 picture user1029108 · Dec 7, 2011 · Viewed 20.6k times · Source

Iam using PHP,Smarty configuration.

Iam getting an array in PHP and sent it to tpl.I would like to make a javascript array in tpl from that php array.

PHP ARRAY

Array
(
    [0] => Array
        (
            [dt] => 2011-12-02
            [number] => 3
        )

    [1] => Array
        (
            [dt] => 2011-12-05
            [number] => 3
        )

    [2] => Array
        (
            [dt] => 2011-12-07
            [number] => 2
        )

)

and I want to get it as a java script array in tpl

s1 = [[[2011-12-02, 3],[2011-12-05,3],[2011-12-07,2]]]; 

Answer

JohnP picture JohnP · Dec 7, 2011

You'd have to loop through it to generate that array

<script>
   var arr = [];
   <?php foreach ($arr as $item) : ?>
   arr.push(['<?php echo $item['dt']?>', <?php echo $item['number']?>]);
   <?php endforeach; ?>
</script>

This will give you an array of arrays.

However, I would do it in another way. I'd just encode it with json and use it as an object

<script>
   var data = <?php echo json_encode($arr)?>;
   for (var x in data) {
      //data[x].dt;
      //data[x].number;
   }
</script>