如何在smarty嵌套的foreach循环中避免数组元素的递归外观?

时间:2014-04-27 16:18:50

标签: arrays loops foreach smarty

我有两个阵列:

$data.applicable_states
Array
(
[applicable_states] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 4
        )
)

另一个数组是all_states

Array
(
    [0] => Array
        (
            [id] => 1
            [state_name] => Alabama
            [abbreviation] => AL
            [created_at] => 1398342353
            [updated_at] => 1398342353
        )

    [1] => Array
        (
            [id] => 2
            [state_name] => Alaska
            [abbreviation] => AK
            [created_at] => 1398342353
            [updated_at] => 1398342353
        )

    [2] => Array
        (
            [id] => 3
            [state_name] => Arizona
            [abbreviation] => AZ
            [created_at] => 1398342353
            [updated_at] => 1398342353
        )

    [3] => Array
        (
            [id] => 4
            [state_name] => Arkansas
            [abbreviation] => AR
            [created_at] => 1398342353
            [updated_at] => 1398342353
        )

    [4] => Array
        (
            [id] => 5
            [state_name] => California
            [abbreviation] => CA
            [created_at] => 1398342353
            [updated_at] => 1398342353
        )
)

现在我想将第二个数组中的所有元素打印到一个selct控件中,但是必须显示所选择的元素,这些元素的id与第一个数组匹配。因此,我写了以下逻辑,但它没有工作。

<select id="example28" multiple="multiple" name="applicable_states[]">
    {foreach from=$all_states item=state key=key}
      {foreach from=$data.applicable_states item=pre key='index'}
        <option value="{$state.id}" {if $state.id == $pre} selected="selected"{/if}>  {$state.state_name}</option>
      {/foreach}
    {/foreach}
</select>

执行上面的代码后,我获取所选状态的名称,但每个状态名称重复四次(即等于第一个数组中包含的元素总数)。如何避免这种重复的元素。请有人帮帮我。

1 个答案:

答案 0 :(得分:0)

看看“Smarty最佳实践” - http://www.smarty.net/best_practices。在您的情况下,您混合应用程序逻辑和视图层数据。结果你就遇到了问题。

如果将逻辑移入PHP文件(逻辑层)并将结果传递给模板,则可以轻松解决此类问题。例如。

PHP:

$states_data_for_select = $all_states;

foreach($states_data_for_select as $key => $state) {
    $id = $state['id'];
    $states_data_for_select[$key]['is_selected'] = in_array($id, $applicable_states);
}

Smarty模板:

<select id="example28" multiple="multiple" name="applicable_states[]">
    {foreach from=$states_data_for_select item=state}
        <option value="{$state.id}" {if $state.is_selected}selected="selected"{/if}> {$state.state_name}</option>
    {/foreach}
</select>