【问题标题】:Creating nested JSON with mysql and PHP使用 mysql 和 PHP 创建嵌套 JSON
【发布时间】:2019-01-10 01:57:06
【问题描述】:

所以,我一直在尝试创建一个嵌套 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);
}

【问题讨论】:

标签: php mysql json


【解决方案1】:

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

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

【讨论】:

  • $databaseResult 中有什么?
  • 无论您的数据库结果是什么,在我回答问题时您没有显示。替换您自己的详细信息。
猜你喜欢
  • 2018-09-05
  • 2017-07-18
  • 2015-07-21
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2018-09-20
  • 2016-08-09
  • 2013-03-13
相关资源
最近更新 更多