Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value count in an array with smarty

Tags:

php

smarty

I have an array called $mydata that looks like this:

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)

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

like image 207
Phil Avatar asked Oct 18 '12 17:10

Phil


3 Answers

have you tried this?:

{$mydata|@count}

where count is passing the php function count()

like image 51
pythonian29033 Avatar answered Nov 20 '22 11:11

pythonian29033


PHP 5.3, 5.4:

As of Smarty 3 you can do

{count($mydata)}

You can also pipe it in Smarty 2 or 3:

{$mydata|count}

To count up "type" values you'll have to walk through the array in either PHP or 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+:

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

{$type_count = array_count_values(array_column($mydata, 'type'))}
Count of type 2: {$type_count['2']}
like image 43
Matt S Avatar answered Nov 20 '22 13:11

Matt S


You can also use:

{if $myarray|@count gt 0}...{/if}
like image 5
crmpicco Avatar answered Nov 20 '22 13:11

crmpicco