【问题标题】:How to parse this JSON object in Symfony如何在 Symfony 中解析这个 JSON 对象
【发布时间】:2017-04-27 00:39:27
【问题描述】:

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 控制器

 /**
     * @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,
        );
    }

树枝:

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

我上面代码的最终结果如下:

BlahBlahBlah #1YaddaYaddaYadda #2BlahBlahBlah #3

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

在这里使用 Symfony3。

【问题讨论】:

  • 您好。我的回答解决了问题吗?如果是,请单击答案旁边的复选标记以将其标记为正确;如果没有,请评论您可能还需要什么帮助。谢谢!

标签: php json symfony twig


【解决方案1】:

如果你只需要标题,它会是这样的:

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

如果您在我的 JSON Twig article 上了解它,那可能会帮助您实现所需。


编辑#2

基于cmets,如果for循环有问题,可以试试这个:

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

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

https://twigfiddle.com/ua9ebs

确保使用 php 函数 json_decode 将 JSON 从 Controller 传递到 twig 模板,以使其正常工作。应该是直截了当的。

【讨论】:

  • 在这种情况下它不起作用,但我现在正在尝试将您的文章应用于我的问题。
  • 是你需要帮助的 for 循环吗?也许我可以更新我的答案....
猜你喜欢
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 2013-07-16
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多