0

所以我将一个 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使用 Smarty ?

4

1 回答 1

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}
于 2012-08-14T08:34:43.547 回答