【问题标题】:how to make a chart with foreach time如何用foreach时间制作图表
【发布时间】:2019-08-23 20:45:38
【问题描述】:

我正在尝试用我的数据库的时间制作一个图表,但我无法让 chartjs “读取”我的数据。

我用 Laravel 和 ChartJS 试试这个。我用这种方式制作其他图表,我的问题只是制作带有日期时间和时间的图表。

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

【问题讨论】:

    标签: javascript laravel time charts


    【解决方案1】:

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

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

    【讨论】:

    • 我做到了你写给我的,但我改变了行:array_push($data, $ot['dayot']); por: array_push($data, $value->tiempo);因为 Laravel 给我一个错误。但是图表没有显示任何内容,只有轴。请问,我该怎么办?
    猜你喜欢
    • 2023-02-10
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多