canvasjs饼图从mysql获取数据

p5fdfcr1  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(307)
$con = mysqli_connect("localhost","root","","final_osa");

if (mysqli_connect_errno($con))
{
    echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
    $data_points = array();

    $result = mysqli_query($con, "SELECT * FROM scholars_list");

    while($row = mysqli_fetch_array($result))
    {        
        $point = array("label" => $row['course'], "y" => $row['student_name']);

        array_push($data_points, $point);        
    }

    echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);

我怎样才能做一个饼图来显示一门课程中有多少学生被学者录取的百分比?谢谢
这是我的js$(document).ready(function(){

$.getJSON("data.php", function (result) {

                var chart = new CanvasJS.Chart("chartContainer", {
                    animationEnabled: true,
                    exportEnabled: true,
                    data: [
                        {
                            type: "pie",
                            showInLegend: "true",
                            legendText: "{label}",
                            indexLabelFontSize: 16,
                            indexLabel: "{label} - #percent%",
                            yValueFormatString: "฿#,##0",
                            dataPoints: result
                        }
                    ]
                });

                chart.render();
            });
        });
uyhoqukh

uyhoqukh1#

像这样格式化数据
假设$records包含您的数据:

$data=array();
foreach ($records as $record) {
    $data[] = array(
        "label"=>$record["student_name"],
        "y"=>$record['course'], //percentage value
    );
}
echo json_encode($data);

js部分:

var chart = new CanvasJS.Chart("chartContainer", {
                title:{
                    text: "Monthly User work details"              
                },
                data: [              
                {
                    // Change type to "doughnut", "line", "splineArea", etc.
                    type: "pie",
                    showInLegend: "true",
                    legendText: "{label}",
                    indexLabelFontSize: 16,
                    indexLabel: "{label} - #percent%",
                    yValueFormatString: "฿#,##0",
                    dataPoints: JSON.parse(result)
                }
                ]
            });
            chart.render();

相关问题