最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

PHP JSON to JavaScript Array - Stack Overflow

programmeradmin1浏览0评论

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)

发布评论

评论列表(0)

  1. 暂无评论