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

标签 php jquery mysql json multidimensional-array

我从 php/mysql 数据库查询中获取一个 json 多维数组(作为 $.ajax 调用成功函数中的“数据”)。 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 端使用它做什么?

最佳答案

$.ajax() 调用的 success 回调中,data 是数组,因此您可以使用 $.each()遍历它:

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

关于php - 如何在多维 JSON 数组中显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14480212/

相关文章:

php - 如何使用 PHP PDO 准备语句选择数据

php - MongoDB (PHP) 中的 $or-Operator

php - 验证主从数据库是否有相同的数据

php - 数据库中的日期条目在哪里 - Cyber​​sourcePK 的 WooCommerce 事件管理器

javascript - 在导航菜单中突出显示当前页面?

jquery - 移动 View : Logo second word not in new line

mysql - 从同一个表中选择两次,结果在同一行

PHP/AJAX 将 XML 数据导入 MySQL 数据库不起作用

javascript - jQuery 的scrollTop/scrollTo 模糊?

MySQL - 'Allow NULL' 的使用