I have an array to loop in smarty. My array look like this: Array( [0]=>( [title] = 'some title' [url] = 'image url' )开发者_如何学Go )....
I loop it in file .tpl and I just want to get top 3 result from this array. My array has the number of item larger than 3. I'm a beginner of smarty someone help me fix this problem. Thank you very much for reading my situation!!
Use {section}: http://www.smarty.net/manual/en/language.function.section.php
if this is the array you posted:
$array = array( array('title' => 'title1', 'url' => 'url 1'),
array('title' => 'title2', 'url' => 'url 2'),
array('title' => 'title3', 'url' => 'url 3'),
array('title' => 'title4', 'url' => 'url 4'),
array('title' => 'title5', 'url' => 'url 5'));
you can use 'section' with 'max' attribute to loop through the first 3 results:
{section name=id loop=$array max=3}
Title {$smarty.section.id.iteration}: {$array[id].title}
URL {$smarty.section.id.iteration}: {$array[id].url}
{/section}
I have no clue about Smarty, but...
...If you're interested in just the first three elements of a large array, why don't you use a for loop instead of a foreach?
I have to out put top 3 results from my array with three difference div layout. The first div is the biggest and the other two div under it in the same row. I add this item array['stt'] = 0 array['stt'] = 1 and in tpl I check {if $array.stt == 1} or {$array.stt == 0} to write out the div with the class I want, I think its not the best way but I can work exactly what I want!! @Kailas Badu: you write carefully and easy to know, thank you very much!
精彩评论