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,显示它可以根据您的需要和指定正常工作:
确保使用 php 函数 json_decode
将 JSON 从 Controller 传递到 twig 模板,以便正常工作。它应该很简单。
关于php - 如何在 Symfony 中解析这个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646770/