Search code examples
phparrayscountsmarty

Count total occurrences in subarray with Smarty


I have this array:

[attributes] => Array
            (
                [1] => Array
                    (
                        [id_attribute] => 1
                        [id_attribute_group] => 1
                        [name] => Rosso
                        [group] => Colore
                        [reference] => WD1012
                        [ean13] => 
                        [isbn] => 
                        [upc] => 
                    )

                [9] => Array
                    (
                        [id_attribute] => 24236
                        [id_attribute_group] => 9
                        [name] => 31 x 86.5 cm.
                        [group] => Dimensioni Fiore 1
                        [reference] => WD1012
                        [ean13] => 
                        [isbn] => 
                        [upc] => 
                    )

                [10] => Array
                    (
                        [id_attribute] => 24237
                        [id_attribute_group] => 10
                        [name] => 31 x 71.5 cm.
                        [group] => Dimensioni Fiore 2
                        [reference] => WD1012
                        [ean13] => 
                        [isbn] => 
                        [upc] => 
                    )

                [11] => Array
                    (
                        [id_attribute] => 24238
                        [id_attribute_group] => 11
                        [name] => 32.5 x 88 cm.
                        [group] => Dimensioni Fiore 3
                        [reference] => WD1012
                        [ean13] => 
                        [isbn] => 
                        [upc] => 
                    )

            )

I want to count the [group] value while searching its value a word:

{foreach from=$variants item=variant}
    {if $variant.group|stristr:'Dimensioni'}
        {$variant.group} 
    {/if}
{/foreach}

Output:

Dimensioni Fiore 1
Dimensioni Fiore 2
Dimensioni Fiore 3

Now I want to count the total occurrences inside arrays (should be 3):

{$variant.group|count}

output:

1
1
1

I have to count the occurrences as if they are 2 or more, it must does something, but the output count only 1 occurrence for each array and not the total. What's the way to achieving this ?

Thanks.


Solution

  • You can use a counter to do this:

    {counter print=false start=0 name=Dimensioni assign=dimensioniCount}
    {foreach from=$variants item=variant}
        {if $variant.group|stristr:'Dimensioni'}
            {$variant.group}
            {counter name=Dimensioni}
        {/if}
    {/foreach}
    
    {if $dimensioniCount>=2}
        <h1>Do something here</h1>
    {/if}