Fork me on GitHub
RSS
 

How to Convert PHP Multidimensional Array to Javascript Object (using jQuery)

29 Sep

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.

 
 

Tags: , , ,

Leave a Reply

 

 
  1. Kate

    May 21, 2011 at 4:15 am

    Thank you so much for posting this. I have been struggling with this very thing for the past few hours and your post helped me solve my problem! Never in my life would I have came up with this solution on my own.

     
  2. David

    July 13, 2011 at 8:09 pm

    Hi double encode isn´t necessary, maybe you can do something like this

    var data = htmlspecialchars(json_encode(aCoders), ENT_NOQUOTES,’UTF-8′);

    You need encode all html tags

     
  3. Manuel

    August 24, 2011 at 8:06 am

    I second Kate, thank you, thank you.

     
  4. Kradz

    December 9, 2011 at 7:33 am

    This is exactly what I was looking for! Man, how did you come up with this? You’re genius! Thank you!

     
  5. Kradz

    December 9, 2011 at 8:58 am

    By the way, alert(object[5].name) does not work for me…

     
  6. Juan Mendes

    December 12, 2011 at 6:13 pm

    You do not need to double encode it. The reason you think you do is because you are trying to call $.parseJSON, which requires a string. Your second call to json_encode is just putting quotes around your JSON. Your code would work just fine like the following, try it out.

    var coders = ;
    for(var language in coders.Ed.languages){
    alert(‘Ed can code in ‘ + language);
    }

     
  7. Juan Mendes

    December 12, 2011 at 6:15 pm

    oops, code didn’t show, should have been

    var coders = <? php print json_encode($aCoders); ?> );

     
    • Chung Xa

      September 12, 2012 at 6:13 pm

      That’s right.. I’ve just experienced with it

       
  8. Laelien

    December 21, 2011 at 2:00 am

    Thank you very much ! I can’t remember how long I’ve been struggling with this problem… but I’m pretty sure it’s been months :P

    Once again, thank you !

     
  9. tag

    February 11, 2012 at 1:49 pm

    Thank you.

    on server side, I encoded it ONLY once as @Juan mentioned.

    And on the client side, used JSON.parse(request.responseText)

     
  10. tropicaltom

    February 17, 2012 at 4:20 am

    Very helpful! After combing through many search find on the subject, this was the simplest, and simple to use on the client side. Thanks!

     
  11. Shashank Rawlani

    March 15, 2012 at 11:35 pm

    I am unable to parse the following json, in javascript – returned from an ajax call to a php page..

    example :
    {“resultset”:[{"url":"http:\/\/www.elated.com\/articles\/cms-in-an-afternoon-php-mysql\/","comments":"CMS ... nice ..\r\n","id":"68"},{"url":"http:\/\/www.elated.com\/articles\/adding-wysiwyg-editor-to-your-site\/","comments":"adding-wysiwyg-editor-to-your-site\/","id":"69"}]}

    I am unable to parse it. has been more than 4 days now and I have burned up a lot… :(
    please help!!
    Thanks in advance !!!
    Regards,
    Shashank Rawlani

     
  12. fhabyo

    July 19, 2012 at 4:06 pm

    hola mi problema similar a este tema, tengo un array en php que imprime esto: 6:[,27,28,],7:[,1,17,1,],11:[,14,] y necesito pasarlo a una variable object de javascript q es:

    var num= { arrayphp } dentro de las llaves necesito el array.

    he probado miles d forma y no me resulta, gracias por las ayudas

     
  13. Mathias

    October 10, 2012 at 12:36 pm

    Thanks you!!! Worked as a charm!!

     
  14. PHP-Nighthawk

    January 21, 2013 at 11:15 pm

    Thanks dude, with this double-time json_decode() you really made my day. THX!

     
  15. Micah

    February 28, 2013 at 12:04 am

    This is brilliant!!!! Awesome code (and much better than anything else I found in searching).

     
  16. Miles Weston

    March 22, 2013 at 6:17 pm

    This was rather interesting and I thoroughly enjoyed working my way through it.It has inspired me to do a better job of my own blog, as I tend to find it quite difficult to come up with any good ideas to post to be fair but it has certainly broadened my horizons. I was curious what plugins you may use to help your SEO and if you can share any tips on that subject I would be very grateful? I don’t use wordpress on my main website as it does not have that feature in the control panel, as it is quite basic but I do have other smaller websites which I want to use wordpress on to give them more of an internet presence. Keep up the good work.Kind regards.

     
  17. best hermes belt

    May 26, 2013 at 12:08 pm

    Your article How to Convert PHP Multidimensional Array to Javascript Object (using jQuery) | edrackham write very well, thank you share!