php - 如何在 Symfony 中解析这个 JSON 对象

标签 php json symfony twig

JSON:

{
  "details": [
    {
      "title": "BlahBlahBlah #1",
      "session_num": "369",
      "author": "Lilyquist J",
      "tradeshow": "AACR General Meeting 2017",
      "show_details": [
        {
          "date": "April 1-5, 2017",
          "location": "Washington DC"
        }
      ]
    },
    {
      "title": "YaddaYaddaYadda #2",
      "session_num": "369",
      "author": "Lilyquist J",
      "tradeshow": "Epcon 97",
      "show_details": [
        {
          "date": "April 1-5, 1997",
          "location": "Anywhere, CA"
        }
      ]
    },
    {
      "title": "BlahBlahBlah #3",
      "session_num": "369",
      "author": "LaDuca H",
      "tradeshow": "(ACMG) 2017",
      "show_details": [
        {
          "date": "April 1-5, 2017",
          "location": "Washington DC"
        }
      ]
    }
  ]
}

Symfony Controller

 /**
     * @Route("/route", name="ag_web_route")
     * @Template()
     *
     * @return array
     */
    public function scientificPosters2Action()
    {
        $posterList = file_get_contents($this->get('kernel')->getRootDir() . '/../web/assets/api/scientific-posters.json');

        $json = json_decode($posterList, true);

        foreach ($json['details'] as $key => $value) {
            echo $value['title'];
        }

        return array(
            'json' => $json,
            'posterList' => $posterList,
        );
    }

Twig :

{% for title in posterList %}
    <h1> {{ title }} </h1>
{% endfor %}

上述代码的最终结果如下:

BlahBlahBlah #1YaddaYaddaYadda #2BlahBlahBlah #3

我无法正确进行for循环,一次只能输出一个标题。它只是将所有标题一起输出到一个 <h1> 中。标签。我在这里缺少什么?我知道$key => $value我缺少一些东西(比如另一个 forloop?),但我无法正确解析它......

这里使用 Symfony3。

最佳答案

如果您只需要标题,则如下所示:

<h1> {{ json['details']['title'] }} </h1>

如果您在我的 JSON Twig article 上阅读了相关内容,这可能会帮助您实现您所需要的。


编辑#2

根据评论,如果for循环有问题,可以试试这个:

{% for item in json['details'] %}
    <h1> {{ item['title'] }} </h1>
{% endfor %}

这是一个 twigfiddle,显示它可以根据您的需要和指定正常工作:

https://twigfiddle.com/ua9ebs

确保使用 php 函数 json_decode 将 JSON 从 Controller 传递到 twig 模板,以便正常工作。它应该很简单。

关于php - 如何在 Symfony 中解析这个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646770/

相关文章:

javascript - D3 节点半径取决于链接数 : weight property

javascript - 如何处理来自 'opaque' 类型的获取响应?

php - 从异步请求中读取 PHP session 数据

php - 如何在 laravel Blade View 中打破 foreach 循环?

c# - NewtonSoft JsonConvert.DeserializeObject 将所有属性返回为 null

php - 如何通过 Twig 用 html 实体转义整个 block ?

forms - Symfony 4 -- 表单最小最大验证

php - 如何让 Doctrine 在 Symfony2 的辅助函数中工作

php - MediaWiki:如何获取用户最近编辑的N篇文章?

php - 处理数据库中的300个字段表单