gpt4 book ai didi

php - 使用 mysql 和 PHP 创建嵌套 JSON

转载 作者:行者123 更新时间:2023-11-29 10:07:27 27 4
gpt4 key购买 nike

所以,我一直在尝试创建一个嵌套的 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"
}
]
},
.
.
.
]

从早上起我就一直在想这个问题,但没有解决。得到了这个答案 - 奥 git _a,但它使用来自 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));

关于php - 使用 mysql 和 PHP 创建嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651180/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com