javascript - how to make a chart with foreach time
问题描述
I'm trying to make a chart with a time of my database, but I can't do that chartjs "read me" my data.
I try this with Laravel and ChartJS. I make other chart with this way, my problem is only to make charts with Datetime and Times.
<script type="text/javascript">
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: [
@foreach ($ambientes as $key => $value)
'{{ $value->mes }}',
@endforeach
],
datasets: [
{
label: "Tiempo de indisponibilidad",
backgroundColor: "red",
data: [
@foreach ($ambientes as $key => $value)
'{{ $value->tiempo }}',
@endforeach
]
}
]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'h:mm'
}
}
}]
},
}
});
</script>
解决方案
首先为标签和数据声明两个数组并将值推入数组
/*Declare array*/
@php $label=array(); $data=array(); @endphp
/*push label and values into array*/
@foreach($ambientes as $key => $value)
@php
array_push($label, $value->mes);
array_push($data, $ot['dayot']);
@endphp
@endforeach
然后 json_encode 脚本中的值
<script type="text/javascript">
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: [<?php echo json_encode($label);?>],
datasets: [
{
label: "Tiempo de indisponibilidad",
backgroundColor: "red",
data: [<?php echo json_encode($data);?>]
}
]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'h:mm'
}
}
}]
},
}
});
</script>
推荐阅读
- python - 评估列表相似性
- angular - 问题:在 post 请求中将对象从 angular 发送到 springboot
- python - 当组中的特定值至少出现两次时,从 pandas 数据框中删除组
- spring-boot - 如何强制二重奏 Spring 云侦探 - Spring MVC/Spring Rest 处理在控制器的处理程序方法参数上设置的 @SpanTag 注释
- operating-system - 设备驱动程序和中断处理程序之间的关系?
- oracle - SAS 错误:WHEN 子句 2 的结果与上述结果的数据类型不同?
- python - 如果使用用户定义的函数输入数字,如何添加数字
- c# - 实体框架核心 DbContextFactory 未注册
- python - 有什么方法可以在 python 中模拟“真实”的鼠标点击和按键?
- java - 初始化会话 Bean - @Startup @Singleton 与 ServletContextListener