I was working on a project today, and I needed to convert a PHP based multidimensional array into a Javascript array, so that I could use it for a dynamic select dropdown (depending on the top level category chosen, the next level select dropdown would be populated with the child elements of the top level category options – if you follow me!).
Anyway, I soon realised that converting the PHP array into a Javascript array was a bad idea, as converting it to a Javascript object would be much much better.
To convert a PHP array (single dimensional, or multidimensional) you simply need to double JSON encode the array. This tutorial relies on jQuery to parse the JSON (using $.parseJSON()), but this isn’t at all necessary – there are other methods to parse JSON. Let’s use the following PHP array as our example:
$aCoders = array(); $aCoders['Ed']['age'] = 25; $aCoders['Ed']['languages'] = array('PHP', 'MySQL', 'JavaScript', 'Objective-C', 'HTML', 'CSS'); $aCoders['Sarah']['age'] = 25; $aCoders['Sarah']['languages'] = array('HTML', 'CSS');
Now we want to use that object with JavaScript. Rather than firing off an AJAX request to get the results we want, seeing as the array is fairly small, we may as well render it in the browser when the page loads – to save on bandwidth and unnecessary requests to the server. To make this array become accessible in Javascript (using jQuery), use the following:
var coders = $.parseJSON(<?php print json_encode(json_encode($aCoders)); ?>);
Yep – you need to double encode the array. This is the key that took me a while to figure out. It adds extra slashes each time you encode, therefore making it render-able in Javascript the second time you encode it.
You can now access your array data using methods similar to the following:
for(var language in coders.Ed.languages){ alert('Ed can code in ' + language); }
Note that javascript objects use dot notation to access the data. If you have a numeric key within your PHP array, you must access it via Javascript using square brackets. For example:
alert(object[5].name);
I hope this helps you to better understand how to translate PHP arrays into Javascript objects, and realise when it’s a good idea to use them, and when it’s still a good idea to just grab what you need by means of an AJAX request.