使用JSON将MySQL数据转换为Highchart的饼图

时间:2019-03-29 11:35:24

标签: javascript php json highcharts

我正在尝试使用从MySQL数据中提取的数据(以JSON格式提取)创建HighCahrts JS的PIE图表。

这是我的php代码:

foreach($row as $rec)  
{  
$json_array['label']=$rec['user_type_detail'];  
$json_array['value']=$rec['id']; 

array_push($json_data,$json_array);  
}  
?> 

我正在获取的JSON是:

[{"label":"Government Doctor","value":"8"},
 {"label":"Private Doctor","value":"5"},
 {"label":"Public Doctor","value":"6"},
 {"label":"Student","value":"4"}
] 

但是问题是页面上没有显示饼图。它只是空白。

我正在使用id =“ container”的div

这是我的脚本:

<script type="text/javascript">

Highcharts.chart('container', {
chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
title: {
    text: 'Browser market shares in January, 2018'
},
credits: {
  enabled: false
},
exporting: { enabled: false } ,
tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
    pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
            style: {
                color: (Highcharts.theme && 
Highcharts.theme.contrastTextColor) || 'black'
            }
        }
    }
},
series: [{
    name: 'Brands',
    colorByPoint: true,
    data:<?php echo json_encode($json_data) ?>
}]
});
</script>

1 个答案:

答案 0 :(得分:0)

您需要使用Highcharts所需的数据格式:

    data: [{
            "name": "Government Doctor",
            "y": 8
        },
        {
            "name": "Private Doctor",
            "y": 5
        },
        {
            "name": "Public Doctor",
            "y": 6
        },
        {
            "name": "Student",
            "y": 4
        }
    ]

实时演示:http://jsfiddle.net/BlackLabel/ce72x3bu/

API参考:https://api.highcharts.com/highcharts/series.pie.data