简体   繁体   中英

How to pass multidimensional array from PHP to Javascript?

I am trying to get array value from JSON string, and I do the work with json_decode PHP.

<?php
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
$jsonDecoded=json_decode($jsonContent,true);
foreach($jsonEncoded['BMS'] as $p){
echo '
ID: '.$p['id'].'
Tipe: '.$p['type'].'
';
echo "<br>";
?>

The PHP code works, and give the result of array from JSON string. And this is my Javascript code

<script>
var bmsdata = <?php echo $jsonDecoded ?>;
alert(bmsdata["1"].id); // For check, i want to see the id of row 1
</script>

But nothing was shown up. Am i doing right so far? Or i missing something to pass the value from PHP to Javascript? Any suggestion will be appreciated.

$jsonDecoded is the decoded json.

Please change

var bmsdata = <?php echo $jsonDecoded ?>;

to

var bmsdata = <?php echo json_encode($jsonDecoded); ?>;

or use the already exisiting variable $jsonContent :

var bmsdata = <?php echo $jsonContent; ?>;

Looks like you're injecting a decoded, PHP-representation of the data into your javascript. You probably (if you want to continue doing it this way) want to echo the encoded version ( jsonContent ) instead.

Ultimately, you might want to rethink the approach. Fetching the data via ajax is often an easier way to work with it, since you don't need to worry about writing bare javascript via php, which has all sorts of escaping issues to get right.

This one should work, as I lookup JSON at http://megarkarsa.com/gpsjson.php ;)

<script>
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
alert(bmsdata.BMS["1"].id); // For check, i want to see the id of row 1
</script>

You just forgot 'BMS' key ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM