在高图表数据中使用字符串


Use string in Highcharts data

我正在使用Symfony2。我将一个字符串传递给显示饼图的视图,并尝试将此字符串传递到数据部分。

我的字符串是:[['EURUSD',7],['GBPUSD',0],['USDEUR',1]]

我从我的symfony控制器中得到它,就像这样:

<?php {{liste}}; ?>

但是当我尝试将其放入这样的数据中时,图表无法正确加载

<script>
...
  series: [{ type: 'pie',name: '',data:  "<?php  {{liste}};?>" 
...
</script>

但是当我这样做时

data: [['EURUSD',7],['GBPUSD',0],['USDEUR',1]]

它有效!

编辑:这是我视图的代码

<html>
<head>
<title>Chart</title>
<!-- Chargement des librairies: Jquery & highcharts -->
<script type='text/javascript' src="{{asset('bundles/user/js/jquery.min.js')}}"></script>
<script type="text/javascript" src="{{asset('bundles/user/js/highcharts.js')}}" ></script>
</head>
<body>
    <p><div align="center">{{liste}}</div></p>
    <p>
<!-- Chargement des variables, et paramètres de Highcharts -->
<script type="text/javascript">
    $(function () {
    var chart;
    $(document).ready(function() {
        Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function(color) {
            return {
                radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 },
                stops: [
                    [0, color],
                    [1, Highcharts.Color(color).brighten(-0.3).get('rgb')]
                ]
            };
        });
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: 'myData'
            },
            tooltip: {
                pointFormat: '<b>{point.percentage}%</b>',
                percentageDecimals: 1
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1) +' %';
                        }
                    }
                }
            },
            series: [{
                type: 'pie',
                name: '',
                data:  "<?php  {{liste}};?>" 
            }]
        });
    });
});</script>
<!-- Affichage du graphique -->
<div id="container" style="width:100%; height:400px;"> 
</div></p>
</body>
</html>

问题是您的字符串已经是 JS 格式,并且您也将其作为字符串传递给模板。删除引号,它应该可以工作。此外,您可能希望使用raw过滤器,以便树枝不会逃脱您的字符。例:

series: [{
    type: 'pie',
    name: '',
    data: {{ liste|raw }}
}]

由于我相信您使用 twig 作为模板引擎,请忘记包含括号的 php。

<script>
...
  series: [{ type: 'pie',name: '',data: "{{liste}}" }]
...
</script>

问题在于 json 对值的解释,因此请使用json_encode过滤器

series: [{
    type: 'pie',
    name: '',
    data: {{ liste|json_encode|raw }}
}]