猿问

使用 Chart.js 和 PHP 动态创建图表

我们目前正在使用客户温度计在完成支持票后调查我们的客户。不幸的是,customerthermometers 小部件看起来很恶心。所以我目前正在尝试使用 Chart.js 创建一个图表,并使用 PHP 从 customerthermometers 的 API 动态获取数据。


PHP-array ($dataPoints) 中的所有部分都在图表中考虑在内,除了“数据”,我真的不知道如何进一步进行。


<?php

$gold = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=1' );

$green = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=2' );

$yellow = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=3' );

$red = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=4' );


$dataPoints = array(

  array( "label" => "Gold Star" , "data" => $gold , "backgroundColor" => "rgba(255,215,0,1)"),

  array( "label" => "Green Light" , "data" => $green , "backgroundColor" => "rgba(0,128,0,1)"),

  array( "label" => "Yellow Light" , "data" => $yellow , "backgroundColor" => "rgba(255,255,0,1)"),

  array( "label" => "Red Light" , "data" => $red , "backgroundColor" => "rgba(255,0,0,1)" )

);

?>

<html>

<head>

<meta charset="utf-8">

<title>Chart Test</title>

</head>


<body>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script src="../assets/chart28/dist/Chart.js"></script>

    <canvas id="myChart" width="100" height="20"></canvas>

<script>

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {

    type: 'bar',

    data: {

        labels: ['Gold Star', 'Green Light', 'Yellow Light', 'Red Light'],

        datasets: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>

    },

    options: {

        scales: {

            yAxes: [{

                ticks: {

                    beginAtZero: true

                }

            }]

        }

    }

});

</script>

    <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>

</body>

</html>


蓝山帝景
浏览 166回答 1
1回答

慕森王

的数据属性$dataPoints应该是一个数组。如果您获得单个值,则必须对其进行转换...$dataPoints = array(&nbsp; array( "label" => "Gold Star" , "data" => array($gold) , "backgroundColor" => "rgba(255,215,0,1)"),&nbsp; array( "label" => "Green Light" , "data" => array($green) , "backgroundColor" => "rgba(0,128,0,1)"),&nbsp; array( "label" => "Yellow Light" , "data" => array($yellow) , "backgroundColor" => "rgba(255,255,0,1)"),&nbsp; array( "label" => "Red Light" , "data" => array($red) , "backgroundColor" => "rgba(255,0,0,1)" ));...
随时随地看视频慕课网APP
我要回答