首页 > 解决方案 > 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>

标签: javascriptlaraveltimecharts

解决方案


首先为标签和数据声明两个数组并将值推入数组

/*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>

推荐阅读