php - Get last N elements from array in smarty

852

how to get last 7 element of php array in smarty ? I wrote code to get last element

      {foreach from=$results item=result name=forsmart}
                                        {if $smarty.foreach.forsmart.last}
                                           {$result->getAvgtimeonpage()|date_format:"%M :%S"}
                                        {/if}
                                    {/foreach}

how to get last 7 elements ?

Best Regards, thanks for help

913

Answer

Solution:

In regards to MarkS answer, you don't have to assign a counter. Smarty has a built-in total.

{foreach from=$results item=result name=forsmart}
       {if $smarty.foreach.forsmart.iteration > ($smarty.foreach.forsmart.total - 7)}
             {$result->getAvgtimeonpage()|date_format:"%M :%S"}
       {/if}
{/foreach}
555

Answer

Solution:

In your foreach:

1) Assignt counter:

{assign var=toShow value=(($results|@count) - 7)}

2) Show items with index greater than counter:

 {foreach from=$results item=result name=forsmart}
       {if $smarty.foreach.forsmart > $toShow}
             {$result->getAvgtimeonpage()|date_format:"%M :%S"}
       {/if}
{/foreach}

In for loop:

1) Assign loop delimiters

{assign var=maxCount value=(($results|@count)}
{assign var=toShow value=($maxCount - 6)}

2) Loop 'n roll:

{for $i=$toShow to $maxCount}
    {$results[i]->getAvgtimeonpage()|date_format:"%M :%S"}
{/for}

Sorry if I've made any misspeling, but I hope you will get the idea.

717

Answer

Solution:

You can try this

$arrayLength = count($results);
for ($i = $arrayLength-7; $i < $arrayLength; $i++) {
    ...
}

I edit my post to provide code for smarty

{assign arrayLength = {$results|@count}}
{for $i=$arrayLength-1 to $arrayLength}
    ...
{/for}

People are also looking for solutions to the problem: C alternative to PHP's explode function

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.