使用smarty获取数组中的值计数

时间:2012-10-18 17:46:18

标签: php smarty

我有一个名为$mydata的数组,如下所示:

Array
(
[0] => Array
    (
        [id] => 1282
         [type] =>2

        )

[1] => Array
    (
        [id] => 1281
        [type] =>1
        )

[2] => Array
    (
        [id] => 1266
          [type] =>2
    )

[3] => Array
    (
        [id] => 1265
        [type] =>3
    )
)

我已将数组分配给smarty $smarty->assign("results", $mydata)

现在,在模板中,我需要打印数组中每个“类型”的数量。任何人都可以帮我这么做吗?

3 个答案:

答案 0 :(得分:18)

PHP 5.3,5.4:

从Smarty 3开始,你可以做到

{count($mydata)}

你也可以在Smarty 2或3中管它:

{$mydata|count}

要计算“类型”值,您必须在PHP或Smarty中遍历数组:

{$type_count = array()}
{foreach $mydata as $values}
    {$type = $values['type']}
    {if $type_count[$type]}
        {$type_count[$type] = $type_count[$type] + 1}
    {else}
        {$type_count[$type] = 1}
    {/if}
{/foreach}

Count of type 2: {$type_count[2]}

PHP 5.5 +:

使用PHP 5.5+和Smarty 3,您可以使用新的array_column函数:

{$type_count = array_count_values(array_column($mydata, 'type'))}
Count of type 2: {$type_count['2']}

答案 1 :(得分:15)

你试过这个吗?:

{$mydata|@count}

其中count传递php函数count()

答案 2 :(得分:4)

您也可以使用:

{if $myarray|@count gt 0}...{/if}
相关问题