PHP JSON to JavaScript Array - Stack Overflow

Is there any good way to pass an PHP Array to my JavaScript as JS Array?if have this PHP Array:array(&#

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 badges
Add a ment  | 

4 Answers 4

Reset to default 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);

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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745563732a4633268.html

相关推荐

  • PHP JSON to JavaScript Array - Stack Overflow

    Is there any good way to pass an PHP Array to my JavaScript as JS Array?if have this PHP Array:array(&#

    16小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信