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.

    评论

报告相同问题?