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?
have you tried this?:
{$mydata|@count}
where count is passing the php function count()
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']}
You can also use:
{if $myarray|@count gt 0}...{/if}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With