0

给定数组:

$fruits = array(
    array(
        'color' => 'red',
        'name' => 'apple'
    ),
    array(
        'color' => 'red',
        'name' => 'cherry'
    ),
    array(
        'color' => 'yellow',
        'name' => 'banana'
    )
);

我试图在 Smarty 中显示它,使其看起来像这样:

red
 1. apple
 2. cherry

yellow
 1. banana

我的代码:

{foreach from=$fruits item=fruit}
    {assign var="current_color" value=$fruit.color}
    <h1>{$current_color}</h1>
        <ol>
            {while $current_color === $fruit.color}
                <li>{$fruit.name}</li>
                {assign var="fruit" value=$fruits|next}
            {/while}
        </ol>
{/foreach}

我的错误结果:

red
 1. apple
 2. cherry

red
 1. cherry

yellow
 1. banana

任何想法我的代码有什么问题?当我在while循环中推进数组指针时,它不会影响foreach循环中的数组吗?

更新 1:

尝试使用 for 循环:

{for $iteration=0 to $fruits|count - 1}
    {assign var="current_color" value=$fruits.{$iteration}.color}
    <h1>{$current_color}</h1>
        <ol>
            {while $current_color === $fruits.{$iteration}.color}
                <li>{$fruits.{$iteration}.name}</li>
                {assign var="iteration" value=$iteration + 1}
            {/while}
            {assign var="iteration" value=$iteration - 1}
        </ol>
{/for}

在 for 循环的第二次迭代中,我收到以下错误:

严重性:通知消息:未定义属性:Smarty_Variable::$step

严重性:通知消息:未定义属性:Smarty_Variable::$total

4

1 回答 1

0

在将它传递给 Smarty 之前,我只是在 PHP 中处理了它。

于 2012-10-02T09:08:39.297 回答