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

I have a PHP array that I want to use in my JavaScript code. I would rather not do something like <?PHP $array['array2name'][0]?>for all the elements in it, since the number is unknown. I was going to make a while loop to write some data to the elements, but I cannot find an easy way to do this at the moment.

How to pass 2d array from PHP to JavaScript in the easiest way?

+3
source share
2 answers

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

json_encode($array);

JSON is easy to understand in jQuery, but for pure JavaScript, see here:

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

+12
source

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 is not the "best" method, but it works.

0
source

Source: https://habr.com/ru/post/1745074/


All Articles