从Twig中的数组键中删除“”括号

时间:2016-04-20 14:20:53

标签: javascript php arrays symfony twig

Twig使我的数组键出错,并将“”括号添加到从symfony2控制器传递的数组键中。

将数组传递给Javascript图形库,该库需要:

[{x:"disabled test object",y:"17",label:"disabled test object"}]

而Twig文档建议的{{ array|json_encode|raw }}以及我读过的其他SO问题会返回不可读的内容:

[{"x":"disabled test object","y":"17","label":"disabled test object"}]



我认为这应该不会很复杂,但到目前为止,通过json_encode选项并没有得出明确的答案。我不确定我能用PHP做些什么,所以我现在已经添加了标签。

编辑:

我现在正尝试使用Twig手动遍历数组。 {{dump(points)}}确认已正确填写

{% set points = chart.dataPoints|json_encode|raw %} <=== this was the problem
dataPoints:
     {% for point in points %}
         {{ dump(point) }}
         { x: {{ point.x }}, y: {{ point.y }}, label: {{ point.label }} }
         {% if loop.lastIndex != true %}
             ,
         {% endif %}
     {% endfor %}

但是这不起作用,因为从未到达转储。这是通过Twig尝试访问foreach中对象的正确方法吗?此代码是几个Twig文档教程的合并。

编辑2,解决方案:

{% set points = chart.dataPoints|json_encode|raw %}将整个数组转换为单个字符串,使得javascript无法解释为数组。删除之后,剩下的就是确保查询结果具有正确的数组键,并在将X轴数据传递给Twig之前对其进行转换。

$i = 0;
$points = array();
/** @var array $query_result*/
foreach($query_result as &$row) {
  foreach($row as $value) {
   $point[] = [
    'x'  => ($i)*10,
    'y' => $value['y'],
    'label' => $value['label']
   ];
   $points[$i] = $point;
   $i++;
  }
}

2 个答案:

答案 0 :(得分:1)

看起来第一个是JavaScript对象,第二个是JSON,尝试在字符串上运行JSON.parse,将其转换回对象:

var fixed = JSON.parse('[{"x":"disabled test object","y":"17","label":"disabled test object"}]');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

答案 1 :(得分:1)

CanotesJS引用不是问题。正如您在下面的示例中看到的那样,"x":有效(我使用了this example):

&#13;
&#13;
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
      title:{
        text: "Top Oil Reserves"
      },
        data: [{
        dataPoints: [
          { x: 1, y: 297571, label: "Venezuela"},
          { "x": 2, "y": 267017,  label: "Saudi" }
        ]
      }]
    });
    
    chart.render();
}
&#13;
<!DOCTYPE HTML>
<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
</head>
<body>
    <div id="chartContainer" style="height: 200px; width: 100%;"></div>
</body>
</html>
&#13;
&#13;
&#13;

所以我们需要为dataPoints:

提供一个JSON数组
  1. 在Controller的函数中定义PHP数组并将其传递给模板:
  2. public function myAction()
    {
        // …
    
        $json = array(
            array(
                'x' => 1,
                'y' => 297571,
                'label' => 'Venezuela',
            ),
            array(
                'x' => 2,
                'y' => 267017,
                'label' => 'Saudi',
            ),
        );
    
        return array(
            // …
            'json' => $json,
        );
    }
    
    1. 在模板中显示数组并将其传递给dataPoints
    2. <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
      <script>
          var json = {{ json|json_encode|raw }};
          window.onload = function () {
              var chart = new CanvasJS.Chart("chartContainer",
              {
                  title:{
                      text: "Top Oil Reserves"
                  },
                  data: [{
                      dataPoints: json
                  }]
              });
      
              chart.render();
          }
      </script>
      <div id="chartContainer" style="height: 300px; width: 100%;"></div>
      

      渲染的输出将是:

      // …
      <script>
          var json = [{"x":1,"y":297571,"label":"Venezuela"},{"x":2,"y":267017,"label":"Saudi"}];
      // …
      

      CanvasJS将能够读取此JavaScript数组并显示图表。