Wednesday, August 28, 2013

Convert PHP associative array to javascript associative array



Convert PHP associative array to javascript associative array, example:
 <?php
$arr = array('price' => 2, 'high' => 3, 'low' => 1);
echo json_encode($arr);
?>
<script>
    var quote=<?php echo json_encode($arr); ?>;
    alert(quote["price"]);
    alert(quote.price);
</script>

PHP function json_encode is used to convert to the JSON representation of a value. Here
json_encode($arr) produce:
{"price":2,"high":3,"low":1}
Then we can create an associative array in JavaScript using
  var quote=<?php echo json_encode($arr); ?>;
We can assess the  array value either via quote["price"] or json_encode($arr).

No comments:

Post a Comment