php - 使用 mysql 和 PHP 创建嵌套 JSON
问题描述
所以,我一直在尝试创建一个嵌套的 JSON,其中数据将来自 MYSQL。
在写了一个长查询后得到了这个 SQL 数据——
+-------------+--------+-------+-------+
| Type | month | Year | Total |
+-------------+--------+-------+-------+
| AR | April | 2018 | 23443 |
+-------------+--------+-------+-------+
| AP | April | 2018 | 11456 |
+-------------+--------+-------+-------+
| AR | May | 2018 | 26483 |
+-------------+--------+-------+-------+
| AR | May | 2018 | 14442 |
+-------------+--------+-------+-------+
需要创建这个 JSON -
[
{
"categorie": "April 2018",
"values": [
{
"value": 23443,
"rate": "AR"
},
{
"value": 11456,
"rate": "AP"
}
]
},
.
.
.
]
从早上开始就一直在敲我的头,但没有解决方案。在 SO - Create nested json object using php mysql中得到了这个答案 ,但它使用来自 SQL 的 2 个查询来获取数据。
在创建将生成 JSON 的 PHP 文件方面需要帮助。
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("SELECT 'AR' as Type,month(DocumentDate) as PeriodM, year(DocumentDate) as PeriodY, sum(Amount) as Total from custledgerentry group by PeriodY,PeriodM union all select 'AP' as Type,month(DocumentDate) as PeriodM, year(DocumentDate) as PeriodY, sum(Amount) as Total from vendledgerentry group by PeriodY,PeriodM");
$json_response = array();
$i=1;
while ($row = mysql_fetch_array($result))
{
$row_array['categorie'] = $row['month'];
$row_array['value'] = $row['question'];
echo json_encode($row_array);
}
解决方案
当您使用要分组的值作为数组键时,这变得很简单:
$results = [];
foreach ($databaseResult as $row) {
$category = "$row[month] $row[Year]";
if (!isset($results[$category])) {
$results[$category] = ['category' => $category, 'values' => []];
}
$results[$category]['values'][] = ['rate' => $row['Type'], 'value' => $row['Total']];
}
echo json_encode(array_values($results));
推荐阅读
- javascript - 将数组中的 HTML 标记配对
- javascript - 使用 Selenium 但不使用 AutoIt 自动上传图像
- postgresql - 如何在 postgres 中创建条件事务?
- node.js - Twilio 消息 API 不允许在其消息正文中使用变量或连接字符串
- azure - 使用 Azure 表单识别器 API 获取模型无效消息
- go - 我可以使用 for c := range 遍历字符串吗
但只使用字符而不使用索引? - angular - Angular 项目的 URL 在 Apache 服务器中运行的问题
- smartsheet-api - 尝试删除我创建的工作区时从 smartsheet API 收到错误
- c# - 一个数字范围内的素数
- mongodb - 有没有办法为此查询使用聚合管道方法