我正在使用OpenCart构建一个遵循MVC结构设计的电子商务平台。现在我试图在仪表板中显示饼图,为此我使用的是Google Charts API。现在,当我只运行第一个数据显示时,它不会在循环中获取数据。这是我的代码。我如何为此设置一个循环?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
$resultViewed = $this->model_report_product->getMostViewed();
$stringResult ="var data= google.visualization.arrayToDataTable([ ['Product', 'Views'],";
foreach($resultViewed as $resultKey => $resultValue)
{
//var_dump($resultValue);
$stringResult = $stringResult . "['".$resultValue['name']."',".$resultValue['quantity']."],";
var_dump($stringResult);
}
$stringResult .= "]);";
$this->data['Viewed'] = $stringResult;
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
答案 0 :(得分:1)
您是否在PHP代码周围使用PHP标记? 从您的代码中,似乎您不是。
无论如何,这种代码应该适合你:
<?php
$resultViewed = $this->model_report_product->getMostViewed();
foreach($resultViewed as $resultValue){
$results[] = "['".$resultValue['name']."', ".$resultValue['quantity']."]";
}
$stringResult = implode(",", $results);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
print $stringResult;
?>
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>