简体   繁体   English

将foreach()输出保存到数组(Smarty)

[英]Save foreach() output into array (Smarty)

How to save foreach output to another array in Smarty and use new array outside of {foreach}? 如何将foreach输出保存到Smarty中的另一个数组并使用{foreach}之外的新数组?

Example: 例:

{foreach name=cats from=$category->subcategories item=n}

/*here would be something like $newArr = ($n->name,$n->url)*/
{/foreach}

<a href="$newarr->name">hi</a>

Don't know much about smarty but easy way to do this in PHP is using the array_push function. 对Smarty不太了解,但是在PHP中执行此操作的简单方法是使用array_push函数。 Or do it with the [] (same thing really) : 或使用[](确实是同一件事):

$newArr = array();
foreach($oldArr as $oldArr) {
   $newArr[] = $n->name,$n->url;
   // EQUIVALENT TO
   array_push($oldArr, $n->name,$n->url);
}

You should do it from code behind. 您应该从后面的代码开始。 Smarty is for View layer and such layer shouldn't have possiblity to do something on variables other than showing it. Smarty适用于View层,该层不应该对变量进行其他操作,而不要显示它。 You can save output to array in php code and then assign it to your view. 您可以将输出保存到php代码数组中,然后将其分配给视图。 But if you really want to do it in smarty you can use php tag http://www.smarty.net/docsv2/en/language.function.php.tpl but I don't recommend it. 但是,如果您真的想聪明地使用它,可以使用php标签 http://www.smarty.net/docsv2/en/language.function.php.tpl,但我不建议这样做。

There is also one interesting tag 还有一个有趣的标签

{append} {附加}

{append} is used for creating or appending template variable arrays during the execution of a template. {append}用于在执行模板期间创建或附加模板变量数组。

http://www.smarty.net/docs/en/language.function.append.tpl http://www.smarty.net/docs/zh/language.function.append.tpl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM