简体   繁体   English

在javascript循环中增加php变量

[英]increasing php variable in javascript loop

Im trying to create a display of charts using chartJS that are dynamic in both the number of charts displayed and its contents. 我试图使用chartJS创建图表显示,这些图表在显示的图表数量及其内容中都是动态的。 I am stuck as to how to iterate through the result set in php while looping through the creation of charts in javascript. 关于如何在javascript中循环创建图表循环遍历php中的结果集时,我陷入困境。 I know that Javascript is processed client side and php is processed server side. 我知道Javascript是处理客户端而php是处理服务器端。 I wrote this code to give you guys a general idea of what i am trying to do. 我写了这段代码,让大家对我想要做的事情有一个大概的了解。 Right now the counter does not increase and i end up with the same graphs, whatever data that comes first in the array. 现在计数器没有增加,我最终得到相同的图表,无论数据中的第一个数据是什么。 In a sense, i need some way of tracking the var i in javascript within php to access the contents in my result set. 从某种意义上说,我需要一些方法来跟踪php中javascript中的var i来访问我的结果集中的内容。

var charts = [];
    <?php $counter = 0; ?>

    for (var i = 0; i < <?php echo sizeOf($readingArray); ?>; i++) {
        var ctx = document.getElementById(i);
        charts[i] = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
            label: 'Actual Readings',
            data: <?php echo json_encode($readingArray[$counter][4], JSON_NUMERIC_CHECK); ?>,
        }, {
            label: 'Threshold',
            data: <?php echo json_encode($readingArray[$counter][5], JSON_NUMERIC_CHECK); ?>,
        }],
        labels: <?php echo json_encode($readingArray[$counter][3]);?>,

        },
        options: {
                zoom: {
                        enabled: true,
                        mode: 'x',
                },
                pan: {
                       enabled: true,
                       mode: 'x',
                },

        },
    });
    <?php $counter++; ?>
  }

You shout assign php variables to js variables and work with them. 你大喊将php变量分配给js变量并使用它们。 Something like this 像这样的东西

var data = '<?php echo json_encode($readingArray); ?>';

Then convert json string to object 然后将json字符串转换为对象

arrayOfObjects = JSON.parse(data)

After that iterate your data and print chart 之后迭代您的数据并打印图表

for (var key in arrayOfObjects) {
console.log(arrayOfObjects[key])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM