Convert multidimensional PHP array to javascript array

I am trying to convert a multidimensional PHP array to a javascript array using a JSON encoder. When I do 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 using now to try and convert it to a JavaScript array:

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

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

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

Is this the correct structure for a multidimensional javascript array? I ask because it keeps giving me this error in the line above:

SyntaxError: Unexpected token o

+6
source share
4 answers

You do not need 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); ?>; 

Then you can access the properties as

 alert(tempArray[0].Key); 
+8
source

It 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> 
+5
source

Do not use parseJSON 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 will give me the console:

 Object { Key="a", Value="asite.com"} 
0
source

Just add single quotes to js function like

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

-1
source

Source: https://habr.com/ru/post/947038/


All Articles