Count total numbers in array

I’m trying to count the total elements that has value in the array on the smarty template.

The array looks like this

Array
(
    [11] => Array
        (
            [country] => Brazil
            [2020] => Array
                (
                    [1] => Array
                        (
                            [Good_1] => 
                            [Good_2] => 
                        )

                    [2] => Array
                        (
                            [Good_1] => 
                            [Good_2] => 
                        )

                    [3] => Array
                        (
                            [Good_1] => 3.59
                            [Good_2] => 
                        )
                      ///

                    [12] => Array
                        (
                            [Good_1] => 
                            [Good_2] => 
                        )

                )

            [2021] => Array
                (
                    [1] => Array
                        (
                            [Good_1] => 4.25
                            [Good_2] => 
                        )

                    [2] => Array
                        (
                            [Good_1] => 
                            [Good_2] => 
                        )

                    [3] => Array
                        (
                            [Good_1] => 4.65
                            [Good_2] => 9.39
                        )

                    /// next months
                )

        )
)

Here I’m pulling data for year 2020 and 2021 for each month 1 – 12. In the example above I have total data =4 because I have data for only 4 months. In other words I have values different than NULL or empty and this total to 4:

3.59, 4.25, 4.65, and 9.39

I’m trying to get this total number = 4 on the smarty. What I’m tried is:

{$data|@count}

What I get on the page is

1 1 1 1

instead of 4. This is the foreach that I show the array

{foreach from=$names_array item=$tor_name name=foo2}
    {$common_data.$tor_name|@count}
    <td>
        <div>{$common_data.$tor_name}</div>
    </td>
{/foreach}

So, how can I show the total count for elements instead of 1 multiple times?

>Solution :

You can try it like this

{counter assign=i start=0 print=false}
    {foreach from=$names_array item=$tor_name name=foo2}
       {if $common_data.$tor_name != 0}{counter}{/if}
       <td>
          <div>{$common_data.$tor_name}</div>
       </td>
    {/foreach}
Available {$i}

What is doing this is to assign +1 to the counter each time when "see" element with value !=0 (not tested with NULL)

Leave a Reply