Best way to pass a 2d array into JavaScript from PHP?

后端 未结 2 1937
清酒与你
清酒与你 2021-01-06 19:47

I have a PHP array I want to use in my JavaScript code. I\'d rather not do something like for all of the elements in it

相关标签:
2条回答
  • Lazy method:

    <script>
    var arr = [];
    
    <?php
        $phparray = array(array(1, 2, 3), array(4, 5, 6));
    
        foreach ($phparray as $i) {
            echo 'arr.push([' . implode(', ', $i) . ']);';
        }
    ?>
    
    </script>
    

    This isn't the "best" method, but hey it works.

    0 讨论(0)
  • 2021-01-06 20:32

    As a JSON Object using the json_encode function. You can then read this with Javascript easily as it is a native javascript object. http://php.net/manual/en/function.json-encode.php

    json_encode($array);
    

    JSON is easily parsable in JQuery, but for pure JavaScript see here:

    http://www.json.org/js.html

    0 讨论(0)
提交回复
热议问题