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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12960598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:33:11  来源:igfitidea点击:

get value count in an array with smarty

phpsmarty

提问by Phil

I have an array called $mydatathat looks like this:

我有一个名为的数组$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
    )
)

I've assigned the array to smarty $smarty->assign("results", $mydata)

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

Now, in the template, I need to print how much of each "type" there is in the array. Can anyone help me do this?

现在,在模板中,我需要打印数组中每种“类型”的数量。谁能帮我做到这一点?

回答by Matt S

PHP 5.3, 5.4:

PHP 5.3、5.4:

As of Smarty 3 you can do

从 Smarty 3 开始,你可以做到

{count($mydata)}

You can also pipe it in Smarty 2 or 3:

您也可以在 Smarty 2 或 3 中使用管道:

{$mydata|count}

To count up "type" values you'll have to walk through the array in either PHP or Smarty:

要计算“类型”值,您必须在 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+:

With PHP 5.5+ and Smarty 3 you can use the new array_columnfunction:

使用 PHP 5.5+ 和 Smarty 3,您可以使用新array_column功能:

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

回答by pythonian29033

have you tried this?:

你试过这个吗?:

{$mydata|@count}

where count is passing the php function count()

其中 count 正在传递 php 函数 count()

回答by crmpicco

You can also use:

您还可以使用:

{if $myarray|@count gt 0}...{/if}