如何在多维JSON数组中显示值

时间:2013-01-23 12:52:02

标签: php jquery mysql json multidimensional-array

我从php / mysql数据库查询中获取了一个json多维数组(作为$ .ajax调用的成功函数中的“data”)。 PHP脚本将其发送到javascript文件,如下所示:

header('Content-Type: application/json');
echo json_encode($arr);

查询可以从数据库中返回一个或多个记录。

console.log(data)似乎只给了我“父”数组中的第一个“子”数组。这是控制台中的内容:

[{id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…},...]
    0: {id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…}
    1: {id:115, branchStateCovered:MN, branchCountyCovered:Benton,…}
    2: {id:116, branchStateCovered:MN, branchCountyCovered:Carlton,…}
    3: {id:117, branchStateCovered:MN, branchCountyCovered:Chisago,…}
    4: {id:118, branchStateCovered:MN, branchCountyCovered:Cook,…}
    5: {id:119, branchStateCovered:MN, branchCountyCovered:Crow Wing,…}
    6: {id:120, branchStateCovered:MN, branchCountyCovered:Isanti,…}
    7: {id:121, branchStateCovered:MN, branchCountyCovered:Itasca,…}
    8: {id:122, branchStateCovered:MN, branchCountyCovered:Kanabec, branchZipCodesCovered:56358, 55051}
    9: {id:123, branchStateCovered:MN, branchCountyCovered:Lake,…}
    10: {id:124, branchStateCovered:MN, branchCountyCovered:Mille Lacs,…}
    11: {id:125, branchStateCovered:MN, branchCountyCovered:Pine,…}
    12: {id:126, branchStateCovered:MN, branchCountyCovered:Saint Louis,…}
    13: {id:127, branchStateCovered:WI, branchCountyCovered:Douglas,…}

在另一个$ .ajax调用中,我正在使用

访问始终是一维的数组
$('label#branchName').text(data['name']);
$('label#branchAddress').text(data['address']);
etc...

但在这种情况下,我需要遍历每个数组,并以与上面类似的方式显示每个数组。

我找到this SO post,但看起来帖子的作者正在创建数组,因为他知道每个“子”数组的“名称”(生产者)。也许我的答案就在那篇文章中,我只是没有看到它。

如何获取输出的多维数组并循环显示每个数组的数组到表中 - 或者我想在HTML端用它做什么?

1 个答案:

答案 0 :(得分:3)

success来电的$.ajax()回调中,data是数组,因此您可以使用$.each()进行迭代:

$.each(data, function(index, element) {
    // use individual element (an object) here, i.e. element.id to get the id
});