如何使我的条形图动态化

时间:2016-11-23 07:20:32

标签: javascript php charts bar-chart

我想表示存储在变量$ dataBycountry中的以下数组数据。 这个变量包含

(
    [0] => Array
        (
            [country] => Russia
            [sessions] => 132
            [users] => 3
            [pageviews] => 261
        )

    [1] => Array
        (
            [country] => India
            [sessions] => 31
            [users] => 20
            [pageviews] => 67
        )

    [2] => Array
        (
            [country] => Austria
            [sessions] => 18
            [users] => 18
            [pageviews] => 53
        )
)

这是我的脚本

var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

var barChartData = {
    labels : ["i want lables also to be dynamic"],
    datasets : [
        {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        },
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,0.8)",
            highlightFill : "rgba(151,187,205,0.75)",
            highlightStroke : "rgba(151,187,205,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]

}
window.onload = function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myBar = new Chart(ctx).Bar(barChartData, {
        responsive : true
    });
}

我希望将这些国家用作标签并动态显示条形图。请给我一个解决方案,如何在脚本中使用$ dataByCountry变量。

1 个答案:

答案 0 :(得分:2)

之前已经介绍过...以下链接应该有所帮助。它概述了几种不同的方法及其优缺点。

How to pass variables and data from PHP to JavaScript?

其他几个重复:

Access PHP variable in JavaScript

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>