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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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)

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

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@L_406_7@:

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

脚本宝典总结

以上是脚本宝典为你收集整理的php – 使用smarty获取数组中的值计数全部内容,希望文章能够帮你解决php – 使用smarty获取数组中的值计数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。