Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  45] [ 6]  / answers: 1 / hits: 17819  / 11 Years ago, tue, june 11, 2013, 12:00:00

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


More From » php

 Answers
2

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);

[#77684] Monday, June 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katia

Total Points: 570
Total Questions: 101
Total Answers: 85

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;