gpt4 book ai didi

php - 根据数组的输出生成 Highcharts

转载 作者:行者123 更新时间:2023-11-29 00:47:49 25 4
gpt4 key购买 nike

更新 我已更新我的代码以响应@MichaelRushton 的评论。我现在正在使用 Highcharts,但无法将输出输出到数据系列。

我现在有从 mysql 查询生成的以下数组,我想将它输出到折线图中。我的 Y 轴应包含金额,x 轴是日期范围,图例是图表上绘制的不同项目。

   // Call the stored procedure
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$array[$row['legend']][$row['date']] = $row['amount'];
//print_r($array);
}


chart = new Highcharts.Chart({

chart: {
renderTo: 'container',
type: 'line'
},

xAxis:
{
categories: [2012-03-01, 2012-03-02, 2012-03-03, 2012-03-04, 2012-03-05, 2012-03-06, 2012-03-07, 2012-03-08, 2012-03-09, 2012-03-10, 2012-03-11, 2012-03-12, 2012-03-13, 2012-03-14, 2012-03-15, 2012-03-16, 2012-03-17, 2012-03-18, 2012-03-19, 2012-03-20, 2012-03-21, 2012-03-22, 2012-03-23, 2012-03-24, 2012-03-25, 2012-03-26, 2012-03-27, 2012-03-28, 2012-03-29, 2012-03-30, 2012-03-31],
},

series:
[

<?php
foreach ($array as $legend => $data)
{
echo '{';
echo "name: '" . $legend . "',";

$values = array();

for ($i = 1; $i <= 31; ++$i)
{
$values[] = isset($data[$i]) ? $data[$i] : 0;
}

echo 'data: [' . implode(', ', $values) . '],';
echo '},';

}
?>
],
}
);

<div id="container" style="width: 100%; height: 400px"></div>
)

这段代码向我展示了以下输出:

series: [ {name: 'Something Tastier',data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],},{name: 'Something Tasty',data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],}, ], } );

除了没有值输出到数据系列外,这似乎是正确的。如果有人有任何进一步的想法,我们将不胜感激。

最佳答案

Highcharts 是我最喜欢的图表选项。将您的数组构造成如下所示可能是值得的:

Array (

[legend_one] => Array
(

[2012-03-01] => 100
[2012-03-02] => 200
[2012-03-03] => 300
...

)

[legend_two] => Array
(

// Day of the month
[2012-03-01] => 100
[2012-03-02] => 200
[2012-03-03] => 300
...

)

...

)

然后您可以像这样使用 Highcharts:

编辑:现在使用完整的日期而不仅仅是日,使月份动态化(使用 $start 变量),并从 0 而不是 1 开始日期迭代器到在使用 strtotime 计算下一个日期时,不再需要 $i - 1

chart = new Highcharts.Chart({

xAxis:
{

categories: [

<?php

// You could dynamically set this date using $_GET/$_POST
$start = '2012-03-01';

$dates = array();

for ($i = 0, $days = date('t', strtotime($start)); $i < $days; ++$i)
{
$dates[] = date('Y-m-d', strtotime($start . ' + ' . $i . ' day'));
}

echo "'" . implode("', '", $dates) . "'";

?>

],

},

series:
[

<?php

foreach ($array as $legend => $data)
{

echo '{';

echo "name: '" . $legend . "',";

$values = array();

for ($i = 0; $i < $days; ++$i)
{

$date = date('Y-m-d', strtotime($start . ' + ' . $i . ' day'));

$values[] = isset($data[$date]) ? $data[$date] : 0;

}

echo 'data: [' . implode(', ', $values) . '],';

echo '},';

}

?>

],

}
);

关于php - 根据数组的输出生成 Highcharts ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com