所以我将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,它们具有相同的结构。
如何使用Smarty以递归方式输出所有id-s:1, 4123, 221, 55, 666
答案 0 :(得分: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}