首页 > 解决方案 > 使用 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);
}

标签: phpmysqljson

解决方案


当您使用要分组的值作为数组键时,这变得很简单:

$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));

推荐阅读