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条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?