将mysql数据检索为特定格式的javascript的问题

问题描述 投票:0回答:1

我正在尝试使用PHP和mysql创建Highchart甘特图。我在从mysql数据库中检索数据时遇到问题。 Highchart Gantt给出的用于存储数据的示例中的格式为:

 cars = [{
   model: 'Nissan Leaf',
   current: 0,
   deals: [{
     rentedTo: 'Lisa Star',
     from: today - 1 * day,
     to: today + 2 * day
   }, {
     rentedTo: 'Shane Long',
     from: today - 3 * day,
     to: today - 2 * day
   }, {
     rentedTo: 'Jack Coleman',
     from: today + 5 * day,
     to: today + 6 * day
   }]
  }}

这是我的表格例如:

kategori |sub categori | start_date | end_date
-----------------------------------------------
cat 1    | sub 1       | 2019-03-01 | 2019-03-04
cat 2    | sub 2       | 2019-03-06 | 2019-03-10

我尝试了以下方法从mysql表中检索数据,以获得示例中给出的确切格式:

查询:

   $query = "SELECT `kategori`, `sub_kategori`, `start_date`, `end_date`, FROM `table` ";

功能:

public function datatable_mini($query)
{
    $stmt = $this->db->prepare($query);
    $stmt->execute();

    if($stmt->rowCount()>0)

    {
        $y=$stmt->rowCount();
        $x=1;

        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
            $start_date = DateTime::createFromFormat('Y-m-d', $row['start_date']);
            $year = $start_date->format('Y');
            $month = $start_date->format('m');
            $day = $start_date->format('d');
        ?>

            {
            <br/>
            <span>Kategori: '<?php print($row['kategori']); ?>',</span>
            <br/><span>current: 0,</span>
            <br/><span>deals: [{</span>
            <br/><span>SubKategori: '<?php print($row['sub_kategori']); ?>',</span>
            <br/><span>Mulai: Date.UTC(<?php print($year); ?>,<?php print($month); ?>,<?php print($day); ?>),</span>
            <br/><span>Selesai: Date.UTC(<?php print(date('Y',strtotime($row['end_date']))); ?>,<?php print(date('m',strtotime($row['end_date']))); ?>,<?php print(date('d',strtotime($row['end_date']))); ?>)</span>
            <br/>
            }]
            <br/>}<?php

            if($x<$y){
                echo ',';
            }
            $x=$x+1;
            ?>
        <?php
        }
    }
    else
    {
       echo "Nothing here...";

    }

}

这是在javascript中:

   cars = [<?php echo $crud->datatable_mini($query); ?>];

当我尝试回显结果时,它提供了所需的完全相同的格式,如示例中所示:

{ 
Kategori: 'cat 1', 
current: 0, 
deals: [{ 
    SubKategori: 'sub 1', 
    Mulai: Date.UTC(2019,03,01), 
    Selesai: Date.UTC(2019,03,04) 
    }] 
}

等等..

但没有显示图表。

如何使用示例中给出的格式将mysql数据检索到javascript中?

javascript php html mysql highcharts
1个回答
0
投票

highcharts无法识别您的对象,因为对象名称不正确且不在数组中(可能您将数组部分固定在未显示的内容中)。

对于您上面粘贴的数据,您需要最终使用以下格式:

[{ 
  data: [{
    name: 'cat 1', 
    id: 'cat 1'
  }, { 
    name: 'sub 1', 
    parent: 'cat 1',
    start: Date.UTC(2019,03,01), 
    end: Date.UTC(2019,03,04),
    completed: {
      amount: 0
    }
  }] 
}],

使用JSFiddle示例:https://jsfiddle.net/ewolden/muj5vx1f/6/

请参阅API以获取所有已定义对象的列表:https://api.highcharts.com/gantt/series.gantt.data

© www.soinside.com 2019 - 2024. All rights reserved.