$days = ["Monday","Tuesday","Wednesday"];
$rates = [40,60,80];
$profit = [];
foreach($days as $day => $value){
foreach($rates as $rate){
$netprofit = $rate* 20;
$profit[$value] = [$rate=> $netprofit];
}
}
$usersChart = new UserChart;
$usersChart->labels($days);
foreach($profit as $key => $value){
$data = array();
foreach ($value as $values){
$data[] = $values;
}
$usersChart->dataset($key, 'line', collect($data));
}
我想将此数组显示为Chartjs线形图。我希望x轴为40,60,80。 Y轴为800、1200、1600。数据集或线应为星期一,星期二和星期三。现在,我将星期一,星期二和星期三作为x轴和线。 600,800等在y轴上。
保持数组原样并将其转换为JSON对象,然后在Javascript中回显它,JavaScript必须在php文件中才能运行,而不是在外部JavaScript文件中。
注意,在此示例中有PHP代码,并且我已将<?php echo $json; ?>
放在javascript代码中。
<html>
<head>
<style>body{width: 800px;}</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
<div>
<canvas id="myChart" width="700px" height="300px"></canvas>
</div>
<?php
$array = array(600, 800, 1200, 1800);
$json = json_encode($array);
?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["20", "40", "60", "80"],
datasets: [
{
label: 'Monday',
borderColor: "#FF9F40",
data: <?php echo $json; ?>,
},
{
label: 'Tuesday',
borderColor: "#FF6384",
data: [600, 800, 1200, 1800]
},
{
label: 'Wednesday',
borderColor: "#219151",
data: [600, 800, 1200, 1800]
}
]
},
// Configuration options go here
options: {}
});
</script>
</body>
</html>