2012-11-24 34 views
3

我需要用smarty对数组排序。我尝试使用this code用smarty排序数组

我的foreach:

{foreach $hooks->addblock as $addblock} 
    <ul> 
    {foreach $addblock|@sortby:"prio" as $value} 
    {[email protected]}: {$value} 
    {/foreach} 
    </ul> 
{/foreach} 

$hooks->addblock后续代码var_dump:

array(5) { 
    ["filed_1"]=> 
    array(5) { 
    ["id"]=> 
    string(7) "filed_1" 
    ["title"]=> 
    string(6) "filed1" 
    ["field"]=> 
    string(20) "This is test filed 1" 
    ["size"]=> 
    int(740) 
    ["prio"]=> 
    int(7) 
    } 
    ["filed_2"]=> 
    array(5) { 
    ["id"]=> 
    string(7) "filed_2" 
    ["title"]=> 
    string(6) "filed2" 
    ["field"]=> 
    string(20) "This is test filed 2" 
    ["size"]=> 
    int(740) 
    ["prio"]=> 
    int(6) 
    } 

所以,我想排序值prio(NUM)升序排列,但它确实不正确出来!
下面的结果:
Output smarty

我想行 “field_2” 成为第一。但我找不到解决方案。

这是修饰符(modifier.sortby.php):http://www.smarty.net/forums/viewtopic.php?p=23628#23628 我也有一个反复出现的错误:

[Sat Nov 24 20:04:52 2012] [error] [client 127.0.0.1] PHP Notice: Uninitialized string offset: 0 in /var/www/libs/plugins/modifier.sortby.php(33) : runtime-created function on line 1

回答

2

PHP Notice: Uninitialized string offset: 0 in /var/www/libs/plugins/modifier.sortby.php(33) : runtime-created function on line 1

这提供了一个线索,如何sortby修改工作。

您链接到的文件说:

The '-' lets you sort in reverse order, and the # lets you sort numerically rather than as a string (you can have '-#age' as well to sort numerically in reverse order)

prio字段是一个整数,但在PHP中,你可以在整数和字符串透明地完成许多操作,该通知表明sortby已经实施串通过分别访问每个字符来排序。这不可能使用整数。

所以,你应该使用#修改:

{foreach $addblock|@sortby:"#prio" as $value} 
          ^
1

不要这样做。排序不是模板引擎应该执行的任务。这显然是业务逻辑,需要进入控制器。

+0

模板为什么不去做呢?以及你提出的解决方案是什么? – Julien

+0

在纯PHP中将数组进行排序,然后交给Smarty,例如使用'uasort($ addblock,function($ a,$ b){return $ a ['prio']> $ b ['prio'];}} );' –

+3

可以说它纯粹是一种表象性的东西。无论哪种方式,这是一个有趣的谜。 –