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'm trying to convert a PHP multidimensional array to a javascript array using the JSON encoder. When I do a var_dump, my php array looks like this:

array (size=2)
  'Key' => string 'a' (length=1)
  'Value' => string 'asite.com' (length=9)

This is the code I'm currently using in my view to try to convert it to a JavaScript array:

var tempArray = $.parseJSON(<?php echo json_encode($php_array); ?>);

Whenever I run this code in the browser, the output of the conversion in the console is this:

var tempArray = $.parseJSON([{"Key":"a","Value":"asite.com"}]);

Is this the correct structure for a javascript multidimensional array? I'm asking because it keeps giving me this error on the line above:

SyntaxError: Unexpected token o

share|improve this question

4 Answers 4

up vote 4 down vote accepted

You do not have to call parseJSON since the output of json_decode is a javascript literal. Just assign it to a variable.

var tempArray = <?php echo json_encode($php_array); ?>;

You should be able then to access the properties as

alert(tempArray[0].Key);
share|improve this answer
    
That worked perfectly, thank you –  user1186173 Jun 11 '13 at 15:41

This worked for me.

<script type='text/javascript'>
<?php
    $php_array = array(
        array("casa1", "abc", "123"), 
        array("casa2", "def", "456"), 
        array("casa3", "ghi", "789" )
    );

    $js_array = json_encode($php_array);
    echo "var casas = ". $js_array . ";\n";
?>

alert(casas[0][1]);

</script>
share|improve this answer

Do not use parseJSON, that's for a string. Just do:

<?php
$php_array = array ('Key'=>'a', 'Value'=>'asite.com');
?>
<html>
<head>

    <script type="text/javascript">
    var tempArray = <?php echo json_encode($php_array); ?>;
    console.log(tempArray);
    </script>
</head>
<body>
</body>
</html>

This give me in the console:

Object { Key="a", Value="asite.com"}
share|improve this answer
    
I didn't realize it was only for strings, thanks for the answer. –  user1186173 Jun 11 '13 at 15:44

Just add single quotes in the js function,like

var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');

share|improve this answer

Your Answer

 
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.