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.
<?PHP $array['array2name'][0]?>
How to pass 2d array from PHP to JavaScript in the easiest way?
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
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.
Source: https://habr.com/ru/post/1745074/More articles:Eclipse ATG-JBoss Project - jbossGet SSL Session ID in asp.net - ssllink (this) in function - javascriptHTML: update title and resume of Google Search - htmlStore os.system or os.popen value - pythonWriting to javascript array in php loop - javascriptReading ini file in C # - stringDisplay Options for Email - c #Can a Linux device driver wait for DMA to complete in device_remove ()? - linux-kernelJQuery resize event for children div - jqueryAll Articles