gpt4 book ai didi

php - ChartJs php数组变成 'labels'和 'datasets'

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:37 24 4
gpt4 key购买 nike

我正在使用 Yii2 和 ChartJS library ,我会问是否可以将数组插入标签和数据范围。

现在这是我的代码:

<?= ChartJs::widget([
'type' => 'line',
'options' => [
'height' => 400,
'width' => 800,
],
'data' => [
'labels' => [$m[0], $m[1], $m[2], $m[3], $m[4], $m[5], $m[6], $m[7], $m[8], $m[9], $m[10], $m[11]],
'datasets' => [
[
'label' => "2018",
'backgroundColor' => "rgba(255,99,132,0.2)",
'borderColor' => "rgba(255,99,132,1)",
'pointBackgroundColor' => "rgba(255,99,132,1)",
'pointBorderColor' => "#fff",
'pointHoverBackgroundColor' => "#fff",
'pointHoverBorderColor' => "rgba(255,99,132,1)",
'data' => [$t[0], $t[1], $t[2], $t[3], $t[4], $t[5], $t[6], $t[7], $t[8], $t[9], $t[10], $t[11]]
],
]
]
]); ?>

如您所见,我正在设置指定每个元素在数组中的位置的值。

我试过这样做:

$tot = "\"" . implode($t, ", \"") . "\"";

上面的代码产生了这样的结果:

"0", "12", "5", "7", ...

但如果我尝试做类似的事情,那是行不通的:

'data' => [$tot] or 'data' => $tot

这可能吗?

最佳答案

我以前是这样做的:

var ctx = document.getElementById("Chart1"); // the element where the chart should be rendered
var myChart1 = new Chart(ctx, {
type: 'line',
data: {
labels: [<?php
foreach( $m as $key => $row) {
echo "'".$row['label']."', "; // you can also use $row if you don't use keys
}
} ?>],

datasets: [{
label: '2018',
data: [<?php
foreach( $t as $key => $row) {
echo "'".$row['data']."', "; // you can also use $row if you don't use keys
} ?>],
backgroundColor => "rgba(255,99,132,0.2)",
borderColor => "rgba(255,99,132,1)",
pointBackgroundColor => "rgba(255,99,132,1)",
pointBorderColor => "#fff",
pointHoverBackgroundColor => "#fff",
pointHoverBorderColor => "rgba(255,99,132,1)",
}]
},
options => [
'height' => 400,
'width' => 800,
]
});

我使用 javascript 创建图表并从我的 php 数组中添加数据。

您可以通过添加具有上述ID的元素来显示图表。

PHP用于处理数据,JS用于显示数据。
所以用JS来显示图表,用PHP来处理数据。

在您的情况下,您可以这样做:

<?php
$data = array(foreach( $t as $key => $row) {
echo "'".$row['data']."', "; // you can also use $row if you don't use keys
});
$labels = array(foreach( $m as $key => $row) {
echo "'".$row['label']."', "; // you can also use $row if you don't use keys
});
?>

<?= ChartJs::widget([
'type' => 'line',
'options' => [
'height' => 400,
'width' => 800,
],
'data' => [
'labels' => $labels,
'datasets' => [
[
'label' => "2018",
'backgroundColor' => "rgba(255,99,132,0.2)",
'borderColor' => "rgba(255,99,132,1)",
'pointBackgroundColor' => "rgba(255,99,132,1)",
'pointBorderColor' => "#fff",
'pointHoverBackgroundColor' => "#fff",
'pointHoverBorderColor' => "rgba(255,99,132,1)",
'data' => $data
],
]
]
]); ?>

关于php - ChartJs php数组变成 'labels'和 'datasets',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828922/

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