Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mysql和PHP创建嵌套JSON_Php_Mysql_Json - Fatal编程技术网

使用mysql和PHP创建嵌套JSON

使用mysql和PHP创建嵌套JSON,php,mysql,json,Php,Mysql,Json,因此,我一直在尝试创建一个嵌套的JSON,其中的数据将来自MYSQL 在编写长查询后获取此SQL数据- +-------------+--------+-------+-------+ | Type | month | Year | Total | +-------------+--------+-------+-------+ | AR | April | 2018 | 23443 | +-------------+--------+----

因此,我一直在尝试创建一个嵌套的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"
             }
          ]
       }, 
  .
  .
  .
  ]
从早上起我就一直在想这个,但没有解决办法。 得到了这个答案,所以- , 但是它使用SQL中的两个查询来获取数据

需要帮助创建将生成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));

请添加您的代码和遇到的错误@Shubham edited.What in$databaseResult?无论您的数据库结果是什么,在我回答问题时您都没有显示。替换你自己的细节。