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);
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

Thanks but console.log says "object" wich is ok, but i need this[[]] Array format for an Plugin.
You should add a semicolon: echo json_encode($myArray);
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

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.