1

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?

4 Answers 4

2

If 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);
0
1

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>
2
  • Thanks but console.log says "object" wich is ok, but i need this[[]] Array format for an Plugin. Commented Apr 17, 2012 at 15:14
  • You should add a semicolon: echo json_encode($myArray); Commented Oct 7, 2015 at 8:28
0

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

0

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)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.