Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Multidimensional PHP array to javascript array

Tags:

javascript

php

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

like image 421
user1186173 Avatar asked Jun 11 '13 15:06

user1186173


People also ask

How to convert PHP array into JS array?

Passing PHP Arrays to JavaScript is very easy by using JavaScript Object Notation(JSON). Method 1: Using json_encode() function: The json_encode() function is used to return the JSON representation of a value or array. The function can take both single dimensional and multidimensional arrays.

How to pass PHP array parameter to JavaScript function?

You can pass array in js by json_encode() php function.. json_encode() will make array into string. you can get array back by saprating that string in js.

Does JavaScript support multidimensional array?

Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.

What is multidimensional array in PHP explain it with simple PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


2 Answers

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);
like image 146
Orangepill Avatar answered Sep 30 '22 11:09

Orangepill


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>
like image 21
smirandac1978 Avatar answered Sep 30 '22 12:09

smirandac1978