douyu4822 2011-12-26 19:02
浏览 54
已采纳

尝试使用JQuery从PHP JSON多维数组中获取数据的问题

I have a multidimensional array which, when echoed in PHP, looks like this:

{
    "11-12-20":{"visits":0,"pageviews":0}
    "11-12-21":{"visits":0,"pageviews":0}
    "11-12-22":{"visits":0,"pageviews":0}
}// etc.

As you can see, the date is the key to the arrays inside the multidimensional array. So I can select an array from the multidimensional array using the date as the key:

$my_multi_array['12-12-12'];

JSON:

$.getJSON('file.php', function(data){
    var test='11-12-29';
    document.write(data.test);
});

When I test that in a browser, nothing is printed on the screen. Also, how would I go about looping through the whole of that array in jQuery and use the data inside that array's array.

I've been at this for hours now, and am pretty frustrated.

  • 写回答

2条回答 默认 最新

  • douqin6785 2011-12-26 19:31
    关注

    The PHP output that you have echoed is not an array, it's a JSON object without comma separators, which means it's not correctly formed.

    If you correct the syntax, you can access the objects in data through the index notation ([]), not the dot operator (.). So instead of accessing data like data.test, you should try data[test].

    Assuming you name your JSON object myJson, here's how you can iterate thought it:

    var myJson = {
        "11-12-20":{"visits":0,"pageviews":0},
        "11-12-21":{"visits":0,"pageviews":0},
        "11-12-22":{"visits":0,"pageviews":0}
    }
    
    for (var item in myJson)
    {
        alert(myJson[item].visits + ", " + myJson[item].pageviews);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看