My understanding is that in order to return a complex PHP variable to Javascript, it should be done via AJAX and json_encode. Could somebody give me an actual example (both PHP and Javascript code) of this? Lets say we have the two-dim array in PHP:

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );

How would we return this to an analogous two dimensional array in javascript using json_encode?

share|improve this question

49% accept rate
how you want array in json? – apis17 Jun 7 '10 at 1:31
1  
Uh... you mean other than the calls to json_encode() and JSON.parse()? – Ignacio Vazquez-Abrams Jun 7 '10 at 1:33
Uh, I don't know. My experience is pretty limited with all of this stuff. That's why I'd like to see some examples. If you know some simple examples then feel free to post them. – GregH Jun 7 '10 at 3:06
feedback

1 Answer

up vote 1 down vote accepted
<?php

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );
?>

<script>
twoDArr = JSON.parse(<?=json_encode($twoDArr)?>)
alert(twoDArr[0][0]) //alerts 'Greg'
alert(twoDArr[0][1]) //alerts '44'
alert(twoDArr[1][0]) //alerts 'Joe'
</script>
share|improve this answer
2  
While this example certainly works, it is generally best to avoid eval when a simple alternative is present. In this case, you could replace the eval statement with JSON.parse(<?=json_encode($twoDArr)?>) to achieve the same effect. – Rookwood Jun 7 '10 at 2:04
@Rockwood: I edited my answer to reflect your suggestion – tipu Jun 7 '10 at 2:11
Sorry for being so obtuse...you have "JSON.parse(<?=json_encode($twoDArr)?>)" What's with the "?=" is that some sort of shorthand? I tried this in my sample page and I get nothing coming back. – GregH Jun 7 '10 at 18:45
Something weird is up...if I echo out json_encode($twoDArr) I get: [["Greg",44,"Owner"],["Joe",23,"Renter"],["Susan",39,"Owner"],["John",32,"Renter‌​"]] That isn't right is it? Should the arrays be separated by a ":"? – GregH Jun 7 '10 at 19:26
1  
Ok, I figured out the problem. I'm not sure why, but the php variable has to be double encoded with JSON_ENCODE. So the JSON.parse line should read: var twoDArr=JSON.parse(<?php echo JSON_ENCODE(JSON_ENCODE($twoDArr))?>); – GregH Jun 7 '10 at 20:50
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.