【问题标题】:Parsing stdClass() object with Smarty用 Smarty 解析 stdClass() 对象
【发布时间】:2012-08-14 06:23:59
【问题描述】:

所以我将一个 PHP stdClass() 对象传递给 Smarty,如下所示,例如:

stdClass Object
(
    [1] => stdClass Object
        (
            [id] => 1
            [children] => stdClass Object
                (
                    [4123] => stdClass Object
                        (
                            [id] => 4123
                            [children] => stdClass Object
                                (
                                    [221] => stdClass Object
                                        (
                                            [id] => 221
                                            [children] => stdClass Object
                                                (
                                                )
                                        ),
                                    [55] => stdClass Object
                                        (
                                            [id] => 55
                                            [children] => stdClass Object
                                                (
                                                )
                                        )
                                )
                        ),
                    [666] => stdClass Object
                        (
                             [id] => 666
                             [children] => stdClass Object
                                 (
                                 )
                        )
                )
        )
)

每个对象都有一个 id 和 children,它们具有相同的结构。 我怎样才能像这样递归地输出所有 id-s:1, 4123, 221, 55, 666 using Smarty?

【问题讨论】:

    标签: php object smarty stdclass


    【解决方案1】:

    递归数据处理有两种选择。首选解决方案是使用{function}。大致如下:

    {function name=printId comma=false data=false}
      {if $comma}, {/if}{$object->id}
      {foreach $data.children as $object}
        {printId data=$object comma=true}
      {/foreach}
    {/function}
    
    {* invoke with: *}
    {printId data=$yourObjectStructure}
    

    另一个 - Smarty2 兼容 - 选项使用 {include}:

    {* recursive-thing.tpl *}
    {if $comma}, {/if}{$object->id}
    {foreach from=$data.children item="object"}
      {include file="recursive-thing.tpl" data=$object comma=true}
    {/foreach}
    
    {* invoke with: *}
    {include file="recursive-thing.tpl" data=$yourObjectStructure}
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 2012-06-24
      • 1970-01-01
      • 2012-11-16
      • 2013-04-29
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多