I have a two dimensional array in php that I need to express as a javascript variable or object. I’ve looked into json encoding it and decoding it for use as a javascript object and this doesn’t make sense since I want to loop through my javascript convert. Expressing the php array as a javascript two dimensional array also doesn’t really make sense because of how complicated multidimensional arrays are in javascript. What is the standard way of doing something like this? As I said, I need to be able to loop through the results. The PHP array holds a number in the first dimension and a page name in the second. I’m trying to find an efficient way to assign ids to a check box associated with each page name. I want to be able to loop through a javascript variable and check each id if the check box has been checked or not. Thanks for your help, I’m not sure how to proceed.
Share
JSON is the perfect way to do this. Javascript Object Notation is simply Javascript syntax to express arbitrary values, objects or otherwise. They’re perfect for transferring PHP values to Javascript:
This is equivalent to you typing:
json_encodegives you a perfect Javascript array which you can loop through or do anything with you’d usually do with a Javascript array. You just need to build the array/object/value you need.What you may need to take care of is that continuously numerically indexed arrays result in JSON arrays, but anything else results in a JSON object. E.g.: