Is there any good way to pass an PHP Array to my JavaScript as JS Array?
if have this PHP Array:
array('XYZ' => 1, 'ABC' => 2);
and i need in my javascript, to print out some plots
var myData = [['XYZ', 1], ['ABC', 2]];
Problem:
If i do console.log(); i get an object and not an array?
I think i have to parse the JSON in my JavaScript part of the application or? Is there any JQuery Plugin to convert this?
Is there any good way to pass an PHP Array to my JavaScript as JS Array?
if have this PHP Array:
array('XYZ' => 1, 'ABC' => 2);
and i need in my javascript, to print out some plots
var myData = [['XYZ', 1], ['ABC', 2]];
Problem:
If i do console.log(); i get an object and not an array?
I think i have to parse the JSON in my JavaScript part of the application or? Is there any JQuery Plugin to convert this?
Share Improve this question edited May 13, 2012 at 16:48 hakre 199k55 gold badges450 silver badges856 bronze badges asked Apr 17, 2012 at 15:02 opHasNoNameopHasNoName 20.8k26 gold badges101 silver badges149 bronze badges4 Answers
Reset to default 2If you want an array as the result of the json_encode you have to present it as non-associative array.
Try something like this:
<?php
$a=array('XYZ' => 1, 'ABC' => 2);
$r=array();
foreach ($a as $k=>$v)
{
$r[]=array($k, $v);
}
echo json_encode($r);
If you do echo json_encode($myArray);
it will echo out:
{
"XYZ": "1",
"ABC": "2"
}
Which you can use in js:
On your php page you can do:
<script>
var myJson = <?php echo json_encode($myArray) ?>;
console.log(myJson);
</script>
you can use json_encode(array)
at php side to conver php array to json. And then you can directly assign it to a js variable like var jsarray = jsonencodedphparray
Jquery has it built in.
in PHP - Echo the response in json format echo json_encode(arr);
In the javascript - parse the json into an object var obj = $.parseJSON(response)