douyu4535 2013-04-10 20:19
浏览 77

smarty中的动态变量数组名称

i am wondering about how to implement a dynamic increment variable, this is my php

<?php 

$sections =5;

for($g=1; $g<=$sections; $g++){
$smarty->assign(array(
        'products-'.$g => $dbvariable,
        'add_display-'.$g => $othervar ));
}

$smarty->assign('number', $sections);
?>

this is my smarty template

{assign var=cnt value=1}
{while $cnt <= $number}
{foreach from=$products-`.$cnt` item=prod name=mysection}
<div class="section-{$cnt}">
// my output here
 <h3>{$products-`$cnt`.name}</h3>
  <img src="{$add_display-`$cnt`.src}">
</div>
{/foreach}
{assign var=cnt value=$cnt+1}
{/while}

can anyone guide me on how to implement the increment dynamic variable on smarty?

it seems like I'm lost here

  • 写回答

1条回答 默认 最新

  • duanletao9487 2013-04-10 22:59
    关注

    I'm not sure if there is a reason for the approach you've started down, but this will be easier to read as an answer than a comment.

    Rather than dynamic variable names, why not just use arrays? This should be equivalent to what you want, I think:

    <?php 
    
    $sections =5;
    
    $products = array();
    $add_display = array();
    for($g=1; $g<=$sections; $g++){
        $products[$g] = $dbvariable;
        $add_display[$g] = $othervar;
    }
    
    $smarty->assign('products', $products);
    $smarty->assign('add_display', $add_display);
    $smarty->assign('number', $sections);
    

    And then (this could probably be simplified further, but I've left it as similar to yours as possible so you can see what I've changed):

    {assign var=cnt value=1}
    {while $cnt <= $number}
        {foreach from=$products[$cnt] item=prod name=mysection}
        <div class="section-{$cnt}">
            // my output here
            <h3>{$prod.name}</h3>
            <img src="{$add_display[$cnt].src}">
        </div>
        {/foreach}
    {assign var=cnt value=$cnt+1}
    {/while}
    

    Incidentally, that <h3> didn't look quite right, so I've guessed at what it should have been.

    评论

报告相同问题?

悬赏问题

  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类