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 と子があります。次のようにすべての id-s を再帰的に出力するにはどうすればよい1, 4123, 221, 55, 666ですか?

4

1 に答える 1

1

再帰的なデータ処理には2つのオプションがあります。推奨される解決策は、{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}

もう1つの-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 に答える