-2

我正在使用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>
4

1 回答 1

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>
于 2012-07-15T21:03:34.960 回答