【问题标题】:get value count in an array with smarty使用 smarty 获取数组中的值计数
【发布时间】:2023-04-01 09:58:02
【问题描述】:

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

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

【问题讨论】:

  • 数组中的每个元素都会有一个类型索引吗?你想计算所有这些还是只计算那些值大于零的?
  • 是的,会有的。并且值总是大于零。

标签: php smarty


【解决方案1】:

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']}

【讨论】:

  • 我确实有 Smarty 3,但我如何从 {count($mydata)} 获取各种“类型”数量?
【解决方案2】:

你也可以使用:

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

【讨论】:

    【解决方案3】:

    你试过了吗?:

    {$mydata|@count}
    

    其中 count 是通过 php 函数 count()

    【讨论】:

    • 它对我有用...但是 |count|@count 有什么区别
    • @Poonam Bhatt,我其实不知道,当我回答这个问题时,我只是做了一些研究,编写了几行代码并想出了这个,那是很久以前的事了
    • @PoonamBhatt 引用:The "@" applies the modifier directly to the array instead of each individual element. 参见:Smarty FAQ
    • 所以,要按预期工作,应该使用@count 来计算数组...谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多