I have a json array in php and I want to pass it to javascript so I can use it with google charts.
If I do this:
var a = <?php echo((json_encode($data))); ?>;
I get the data in the format Name,Value,PHP,78,JAVA,1000,HTML,129 but I want to keep it in the json format that it was in
[["Name","Value"],["PHP",78],["JAVA",1000],["HTML",129]]
because google charts needs to receive it like this. Any idea how to do this?
RNK
5,80211 gold badges72 silver badges144 bronze badges
-
You can't. Only workaround would be using AJAX or something.Andrei P.– Andrei P.2015年03月26日 14:16:42 +00:00Commented Mar 26, 2015 at 14:16
1 Answer 1
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
try it hope this will help...
answered Mar 26, 2015 at 14:18
Vivek Singh
2,4451 gold badge16 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Vickie
no error just still getting it in the wrong format when I test. I think because I am changing it to a javascript variable but I just want to keep it as a json array
Vickie
<?php $data = Array (); $data [] = Array ("Name", "Value"); $data [] = Array ("PHP", 78); $data [] = Array ("JAVA", 1000); $data [] = Array ("HTML", 129); $table = json_encode($data); echo $table ; ?>
Vickie
sorry about how it looks, new to stackoverflow, don't really know how to use it
default