Re: [SMARTY] outputting a foreach in order

From: Date: Mon, 16 Feb 2004 09:12:12 +0000
Subject: Re: [SMARTY] outputting a foreach in order
References: 1  Groups: php.smarty.general 
Request: Send a blank email to php-smarty-general+get-10954@lists.php.net to get a copy of this message
I think the best way to deal with this problem would be sorting the array BEFORE it is assigned. You can define our own sorting function for that: function sort_pref($a,$b) { if($a['Preferences']['position']==$b['Preferences']['position']) return 0; return ($a['Preferences']['position'] < $b['Preferences']['position']) ? -1 : 1; } then you call usort: usort($the_array,"sort_pref"); See also the documentation for usort. With best regards Gabriel Birke -- KONTOR4_Neue Medien Plathnerstraße 5 30175 Hannover Fax: +49 51184 48 98 99 mailto:birke@kontor4.de http://www.kontor4.de Am 16.02.2004 um 08:30 schrieb Vonleigh Simmons: > Hello, > > I have a section of my site that builds up the navigation list. On > the bottom of this email you can find a sample array, the smarty code > and the output. > > The array has a variable called position. The default is for position > not to be set. As it stands the foreach loop outputs the list in the > order in which it receives it (which is the order in which they were > put into the db). > > However I'd like for smarty to output the list in the order in which > it receives it _except_ when the position is explicitly set. For > example a user could add a Home link and set it to position=1. > > I'm not sure how exactly to do this and would appreciate any > suggestion you may have. > > > Vonleigh Simmons [vanlei] > San Francisco, CA > <www.illusionart.com/pi/> > > > Array > ( > [Preferences] => Array > ( > [id] => 2 > [name] => Preferences > [type] => title > [value] => > [position] => > [children] => Array > ( > [Personal Details] => Array > ( > [id] => 1 > [name] => Personal Details > [type] => preferences > [value] => personal_details/ > [position] => > [children] => > ) > > ) > > )... > > The smarty foreach that builds the list looks like so: > > <ul> > {foreach name=category from=$userNavi key=catkey item=category} > {if $category.type eq "title"} > <li class="category">{$category.name}</li> > {else} > <li class="category"><a > href="{$category.value}">{$category.name}</a></li> > {/if} > {foreach name=subcategories from=$category.children > key=subcatkey item=subcategory} > <li class="subcategory"><a > href="{$subcategory.value}">{$subcategory.name}</a></li> > {/foreach} > {/foreach} > </ul> > > The output is then: > > <li class="category">Preferences</li> > <li class="subcategory"><a href="personal_details/">Personal > Details</a></li> > > -- > Smarty General Mailing List (http://smarty.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > >

« previous php.smarty.general (#10954) next »