简体   繁体   English

Twig 循环遍历 JSON

[英]Twig loop through JSON

Array
(
    [page_title] => Slovak RS
    [page_footer] => © Copyright 2017
    [is_published] => published
    [menu] => {
    "id":"1",
    "name": "main_menu",
    "items": [
        "pos1": [
        "display_name" : "Informácie",
        "path"         : "informacie"
    ],
        "pos2": [
        "display_name" : "Videá",
        "path"         : "video"
    ],
        "pos4": [
        "display_name" : "Recepty",
        "path"         : "recepty"
    ],
        "pos5": [
        "display_name" : "Galéria",
        "path"         : "galeria"
    ],
        "pos6": [
        "display_name" : "Osobnosti",
        "path"         : "osobnosti"
    ],
    ],
    "updated_at": "2020"
 }
)

This is data I'm getting into twig template file.这是我进入树枝模板文件的数据。 I want to have menu in single db table stored as json.我想将单个数据库表中的菜单存储为 json。 I can show items like {{ menu }}, {{ page_title }} , but have hard times looping through that json part我可以显示{{ menu }}, {{ page_title }} ,但是很难循环遍历 json 部分

This is what i tried这是我试过的

 {% for item in menu %}
    {{ item.id }}
    {{ item['id'] }}
    {% endfor %}

    {% for key,value in menu %}
    Key : {{ key }}
    Value : {{ value }}
    {% endfor %}

I'm using twig 2.x and I'm newbie我正在使用 twig 2.x 并且我是新手

You should json_decode the JSON first, before you're passing it to twig.您应该对 JSON 进行json_decode ,然后再将其传递给twig With that, you have an array or object, that you can loop through.有了它,你就有了一个数组或对象,你可以循环遍历。

$objJson = json_decode($yourDBArray['menu']);
$arrJson = json_decode($yourDBArray['menu'],true);

In the code you've provided, the JSON is a string and not an array nor an object .在您提供的代码中, JSON 是一个string而不是array也不是object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM