首页 > 解决方案 > 在 chart.js 和 PHP 中循环多行作为标签和数据

问题描述

使用 chart.js 我想创建一个给定股票价格的图表。使用来自 $select_query 的数据获取标签和数据。在这里,我创建了一个从 URL 获取代码名称的动态函数:https ://signal-invest.com/tick/?ticker=LOW

$select_query = $con->prepare("SELECT Date_buy, Name_buy, Price_buy FROM daily_buy_orders WHERE Name_buy = ?");
$select_query->bind_param('s', $ticker); // 's' specifies the variable type => 'string'
$select_query->execute();

我尝试使用 while 循环遍历行但失败了。

<canvas id="myChart" style="border: 1px solid black; margin: 25px 25px" height="300"></canvas>
                <script>
                var ctx = document.getElementById('myChart').getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        //labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                        labels: [<?php
                          $get_dates = $select_query->get_result();
                            while ($rows = mysqli_fetch_assoc($get_dates)) {
                            $dates = $rows["Date_buy"];
                            echo ''.$dates.'';
                            }
                            ?>],
                        datasets: [{
                            label: '# of Votes',
                            //data: [12, 19, 3, 5, 2, 3],
                            data: [<?php
                            $get_prices = $select_query->get_result();
                            while ($rowss = mysqli_fetch_assoc($get_prices)) {
                            $prices = $rowss["Price_buy"];
                            echo ''.$prices.'';
                            }
                            ?>],
                            backgroundColor: 'rgba(255, 99, 132, 0.2)',
                            borderColor: 'rgb(75, 192, 192)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
                </script>

上面的代码与我下面的表格相混淆。创建表时,while 循环实际上有效。在为chartjs中的标签和数据执行while循环时,我尝试使用相同的想法,但没有奏效。

           <table style="width:50%" border="solid">
            <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Date of signal</th>
             </tr>
                <?php
                $result = $select_query->get_result();
                while ($row = mysqli_fetch_assoc($result)) {
                $name_buy = $row["Name_buy"];
                $price_buy = $row["Price_buy"];
                $date = $row["Date_buy"];
              echo buy_table($name_buy, $price_buy, $date);
                }
                ?>
            </table>

标签: phpchart.js

解决方案


尝试使用 PHP 代码动态构建 JS 数组绝不是一个好主意。相反,在 PHP 中构建数组并用于json_encode将其传递给 JS (或者更好的是,使用模板引擎并将其与数据属性一起传递,但这是另一个话题)

此外,您正在尝试多次循环结果,我不确定这是可能的。很久没有使用原生的mysqli函数了。

首先,获取数据并构建您需要在 PHP 中传递给 Chart.js 的数组:

$statement = $con->prepare("SELECT Date_buy, Name_buy, Price_buy FROM daily_buy_orders WHERE Name_buy = ?");
$statement->bind_param('s', $ticker); // 's' specifies the variable type => 'string'
$statement->execute();
$result = $statement->get_result();

$dates = [];
$prices = [];
while ($row = $result->fetch_assoc()) {
    $dates[] = $row['Date_buy'];
    $prices[] = $row['Price_buy']
}

现在您可以以更简洁的方式将其传递给图表:

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?php json_encode($dates); ?>,
        datasets: [{
            label: '# of Votes',
            data: <?php json_encode($prices); ?>,
        }]
    }
}

我没有测试过这个,但它给了你这个想法

编辑:这将返回以下输出:“LOWArrayLOWArrayLOWArrayLOWArray”。其中 Name_buy 为 LOW,这意味着第二个打印语句被窃听。如何解决这个问题?

    $arrDates = array();
    $arrPrices = array();
    $arrNames = array();
    // $dates = [];
    // $prices = [];
    // $names = [];
    $result = $select_query->get_result();
    while ($row = mysqli_fetch_assoc($result)) {
        $arrDates[] = $row['Date_buy'];
        $arrPrices[] = $row['Price_buy'];
        $arrNames[] = $row['Name_buy'];
        print($row['Name_buy']);
        print($arrNames);
        }

推荐阅读