Generating Visual Statistical Charts with PHP and ECharts
This article demonstrates how to use a PHP interface to retrieve data from a MySQL database and employ the ECharts library to create dynamic visual statistical charts, guiding developers through preparation, data extraction, and chart generation steps, including code examples for a bar chart.
创建容器
// 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 指定图表的配置项和数据 var option = { title: { text: '用户年龄分布图' }, tooltip: {}, legend: { data: ['年龄'] }, xAxis: { data: ['18岁以下', '19-25岁', '26-35岁', '36-45岁', '46岁以上'] }, yAxis: {}, series: [{ name: '年龄', type: 'bar', data: [] }] }; // 将后台获取到的数据与option中的数据对应 option.series[0].data = [ { value: 0, name: '18岁以下' }, { value: 0, name: '19-25岁' }, { value: 0, name: '26-35岁' }, { value: 0, name: '36-45岁' }, { value: 0, name: '46岁以上' } ]; <?php foreach ($data as $v) { if ($v["age"] < 18) { echo "option.series[0].data[0].value = option.series[0].data[0].value+1;"; } if ($v["age"] >= 19 && $v["age"] <= 25) { echo "option.series[0].data[1].value = option.series[0].data[1].value+1;"; } if ($v["age"] >= 26 && $v["age"] <= 35) { echo "option.series[0].data[2].value = option.series[0].data[2].value+1;"; } if ($v["age"] >= 36 && $v["age"] <= 45) { echo "option.series[0].data[3].value = option.series[0].data[3].value+1;"; } if ($v["age"] > 45) { echo "option.series[0].data[4].value = option.series[0].data[4].value+1;"; } } ?> // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option);
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.