Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a PHP array I want to use in my JavaScript code. I'd rather not do something like <?PHP $array['array2name'][0]?> for all of the elements in it as it's number is unknown. I was going to do a while loop to write in some of the data into elements but I cannot seem to find an easy way to do this currently.

How do I pass a 2d array from PHP to JavaScript in the easiest way possible?

like image 861
133794m3r Avatar asked Apr 13 '26 17:04

133794m3r


1 Answers

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

like image 136
Gazler Avatar answered Apr 16 '26 05:04

Gazler