【问题标题】:Three nested for-loops do not seem to work三个嵌套的 for 循环似乎不起作用
【发布时间】:2016-05-13 13:10:02
【问题描述】:

我目前正在开发一个关于 Symfony 2.8 的网站项目。 但我有一个问题:我想显示来自 JSON 对象的信息。但是,我需要执行三个嵌套的 for 循环才能执行我想要的操作。

这是我的代码块:

我要浏览的数组:

element stdClass Object =>
(
[partschemes] => Array
(
    [0] => ( [id] => 1 )
)
[decodedPartitions] => Array
    (
        [0] => stdClass Object
            (
                [partitions] => Array
                    (
                        [0] => stdClass Object
                            (
                                [name] => WINDOWS
                                [type] => primary
                                [size] => -
                                [filesystem] => fat32
                            )

                        [1] => stdClass Object
                            (
                                [name] => DATA*
                                [type] => primary
                                [size] => 256 Mo
                                [filesystem] => fat32
                            )

                    )

            )

    )
)

我的树枝模板:

{% for i, disk in element.decodedPartitions %}
        <tr>
            <th class="text-center" rowspan="3" width="10%">
                <a href="{{ app.request.baseUrl }}/partscheme/details/{{ element.partschemes[i].id }}" class="btn btn-info" title="{{ 'button.details' | trans }}">Disk {{ i }}</a>
            </th>
        </tr>

        {% for j, part in disk.partitions %}
        <tr>
            <th class="text-center" width="10%">Partition {{ j }}</th>
            <td>
                {% for k, partInfo in part %}
                    {{ k }}: {{ partInfo }}<br>
                {% endfor %}
            </td>
        </tr>
        {% endfor %}
    {% endfor %}

结果,生成的页面向我显示,没有不同分区的信息:

---------------------------------
       | Partition 0 |          |
Disk 1 |-------------|----------|
       | Partition 1 |          |
---------------------------------

【问题讨论】:

  • 您不能直接在 twig 中迭代对象属性(part 是对象,而不是数组!)。您可以更改导出的变量,使part 是数组,或者您可以查询具体属性,例如part.namepart.type,...或者您可以使用自定义过滤器将对象转换为数组,如下所述: stackoverflow.com/questions/11841515/…

标签: php symfony for-loop nested twig


【解决方案1】:

感谢Miro,我能够迭代我的 JSON 对象。

原因是不可能直接在 Twig 中迭代 stdClass 对象。所以我在我的json_decode控制器中添加了一个参数。

将 JSON 转换为 stdClass 对象:json_decode($json)

将 JSON 转换为关联数组:json_decode($json, true)

更多关于json_decode的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多