Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a two-dimensional php array, $phpar, in which both dimensions are indexed (0,1,2,...), and all values are plain text. Within a JavaScript function, I want to convert this array into a two-dimensional JavaScript array. I know the following code doesn't work, but it illustrates what I want to do.

jsfunction() {
    var jsarray = new Array();
    jsarray = <?php json_encode($phpar); ?>;
}

If the returned value is something other than a regular js array, like a JSON string, I need some help parsing that into what I want, please.

share|improve this question

closed as unclear what you're asking by T.J. Crowder, Antti Haapala, chrylis, RandolphCarter, Adam Arold Aug 26 '13 at 8:04

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
What you've done should work just fine, assuming $phpar really contains a two-dimensional array. (Except there's no need for the = new Array() part at all, you're just creating an array to throw it away on the next line). So what you want to do, if this isn't working, is look at what the browser receives for it, and update the PHP variable so it really contains a two-dimensional array. –  T.J. Crowder Aug 25 '13 at 17:29
    
Note that there is a possible security issue here: when $phpar depends on user-input, it might contain a string with a </script> tag, followed by malicious stuff to be injected in your web page. –  AardvarkSoup Aug 25 '13 at 17:50
    
Continued: adding the options JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS to json_encode would prevent this and some other vulnerabilities, but I wouldn't dare to say that this prevents all possible attacks. It's probably better to avoid inserting dynamic content in your JS scripts directly. –  AardvarkSoup Aug 25 '13 at 17:58
    
@T.J.Crowder Maybe I'm just too tired for this today or something, but can you please explain why everyone's talking about JSON.parse? Is it me missing something, or is it plain hogwash? I'm just making sure I'm not the only one on this. O.o –  Christian Aug 25 '13 at 19:59
    
@AardvarkSoup That's why you json_encode the stuff!! –  Christian Aug 25 '13 at 20:03

2 Answers 2

What are you actually trying accomplish here in terms of you application's functionality?

PHP is a backend language and JavaScript is a frontend language. If you need the frontend to retrieve an object from the backend to use in your JavaScript you should use Ajax as opposed to putting PHP code inside your JavaScript.

Your Ajax method will call the relevant PHP method using an MVC-style URL ('/mycontroller/mymethod'). The PHP method should use use associative array(s) since JSON objects are key-value pairs. You should json_encode the array before returning it.

Here's some sample PHP code:

<?php #foo.php

public function bar() {
    $array = ('first-name' => 'John', 'last-name' => 'Doe');
    return json_encode($array);
}

On the frontend, your JSON object will consist of the same key value pairs as your associative array:

var getBar = function() {
    $.get('/foo/bar', function(data) {
        var string = 'My name is ' + data.first-name + ' ' + data.last-name';
        alert(string);
    }, json);
};
share|improve this answer
    
@Christian I deleted my original comments B/C I think we got a bit too personal To your point, there are some limited circumstances where it might make sense to have the backend populate an inline JSON object. To my points: 1. if one goes that route it's better to have the controller do the JSON encoding and print the object to a hidden div as opposed to using PHP inside of JS in the view; 2. Unobtrusive JS is usually better than inline or embedded JS B/C It's reusable, easier to maintain, and more performant. Finally, tight coupling impedes flexibility, scalability, and maintainability.Cheers –  Neil Girardi Aug 26 '13 at 12:15
    
Cleaned up a bit myself. Must admit that my initial comment was probably too harsh. Your point is very valid, but one might as well have a JS view and output all these details registered throughout the system. Please also note that you've been hinting at MVC, which is only one pattern one might decide to work with. And finally, with this in mind, we don't know where the OP is going to use this code and frankly I leave this all up to him. –  Christian Aug 26 '13 at 17:52
    
I agree 100%. Cheers sir! –  Neil Girardi Aug 26 '13 at 23:01

I'm not exactly sure where your problem is...but the basic operation of json_encode simply looks like:

<script type="text/javascript">

    var jsarray = <?php echo json_encode($phpar); ?>;

</script>

Frankly, I don't see why the other people are suggesting throwing a javascript-compatible object/array into a string, and worse the way they did it is wrong. If you want a JSON object string, this is the correct way of doing it:

<script type="text/javascript">

    var jsarray_string = <?php echo json_encode(json_encode($phpar)); ?>;
    //                                   ^           ^------ php array to js array
    //                                   '------------------ php string to js string
</script>

By the way, javascript objects can be accessed like arrays. Example:

var myArray = {1: 'hi', 2: 'bye'};
alert(myArray[2]); // this works!

The only difference is that myArray is not really a javascript array, eg, myArray.constructor is not Array().

share|improve this answer
    
Got it, I'm with you now. This is a comment, not an answer. It's the same as my original comment: What the OP is doing should work. Until we have further information, it's impossible to answer the question. –  T.J. Crowder Aug 25 '13 at 21:16

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