我使用最新的 codeigniter 框架,并且正在开发数据库搜索功能,该功能根据表单输入搜索我们的数据库,结果以数组形式发送到 View ,其中包含模型中生成的搜索的所有数据。
我尝试使用这些数据来填充 morris.js 图表,但遇到了困难。我可以使用 php 提取所需的数据,但如何使用该数据来填充图表?
这是基本的图表js:
new Morris.Donut({
// ID of the element in which to draw the chart.
element: 'donutEg',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{label: "Positive", value: 7},
{label: "Negative", value: 26},
{label: "Pending", value: 786},
{label: "Contact Clinic", value: 243},
{label: "Unspecified", value: 1}
],
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
});
我想使用这些 php 变量填充结果:
<?php $pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($chart as $item) {
if ($item['result'] === 'Positive') {
$pos++;
}
elseif ($item['result'] === 'Negative') {
$neg++;
}
elseif ($item['result'] === 'Pending') {
$pen++;
}
elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
}
else{$misc++;}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
}; echo 'Positive Results: ' . $pos . '<br />' . "Negative Results: " . $neg . '<br />' . "Pending Results: " . $pen . '<br />' .
"Contact Results: " . $cont . '<br />' . "Misc Results: " . $misc . '<hr />'; ?>
我如何使用数组“$res”来填充图表,使用命名键作为图表标签,并使用相应的值作为值?
干杯
** 更新 ** 按照 @nando 的建议使用此代码,我只得到一段:值为 NaN 的正值(尽管值是数字,正值 = 7)
new Morris.Donut({
// ID of the element in which to draw the chart.
element: 'donutEg',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{label: "Positive", value: "<?php echo $res['Positive'] ?>"},
{label: "Negative", value: "<?php echo $res['Negative'] ?>"},
{label: "Pending", value: "<?php echo $res['Pending'] ?>"},
{label: "Contact Clinic", value: "<?php echo $res['Contact the Clinic'] ?>"},
{label: "Unspecified", value: "<?php echo $res['Misc'] ?>"}
],
});
** 进一步更新 ** 我有以下 JSON 数组:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
如何将这些值分配给我的图表?
最佳答案
你可以用 <?php echo ?>
来做到这一点在 JavaScript 端:
new Morris.Donut({
// ID of the element in which to draw the chart.
element: 'donutEg',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{label: "Positive", value: <?php echo $pos ?>},
{label: "Negative", value: <?php echo $neg ?>},
{label: "Pending", value: <?php echo $pend ?>},
{label: "Contact Clinic", value: <?php echo $cont ?>},
{label: "Unspecified", value: <?php echo $misc ?>}
]
});
关于javascript - 如何根据通过 Controller 发送的结果动态填充 morris.js 图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45634035/