【问题标题】:Assign values to PHP Smarty array via for loop通过 for 循环为 PHP Smarty 数组赋值
【发布时间】:2011-03-25 03:12:01
【问题描述】:

我是一个 PHP 新手,但我正在尝试通过 for 循环将值(本周的日期)分配给 smarty 数组。不幸的是,经过一个小时的搜索,我无法弄清楚如何解决这个问题。

我能做的最好的事情是将这些日期值分配给七个单独的变量(而不是一个包含七个值的数组)。我的代码如下。谁能帮助我将这些值加载到数组而不是单个变量中?提前感谢您的帮助。

global $smarty;

// Set current date and parse about any English textual datetime description into a Unix timestamp
$ts = strtotime('now');

// Calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) $offset = 6;

// Calculate timestamp for the Monday
$ts = $ts - $offset*86400;

// This is where I want to assign dates to a smarty array, not individual variables
for ($i=0; $i<7; $i++, $ts+=86400){
    $smarty->assign('day'.$i,date("m/d/Y l", $ts));
}

【问题讨论】:

    标签: php arrays variables loops smarty


    【解决方案1】:

    你为什么不把数组做成这样:

    $days = array();
    for ($i=0; $i<7; $i++, $ts+=86400){
        $days[] = date("m/d/Y l", $ts);
    }
    $smarty->assign('days' , $days);
    

    然后在 smarty 中你可以使用 foreach 循环来显示数组。

    smarty 会是这样的:

    {foreach from=$days key="ind" item="day"}
      {$day}<br />
    {/foreach}
    

    【讨论】:

    • 感谢萨宾的回复!我今晚会试试看。
    • 是的,工作就像一个魅力。感谢您对语法的帮助!
    猜你喜欢
    • 2016-01-17
    • 2019-06-27
    • 1970-01-01
    • 2015-03-01
    • 2015-06-09
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多