Re: [SMARTY-DEV] enhanced foreach loops
| From: | Kerry Wilson | Date: | Thu, 16 Nov 2006 19:21:32 +0000 |
| Subject: | Re: [SMARTY-DEV] enhanced foreach loops | ||
| References: | 1 2 | Groups: | php.smarty.dev |
| Request: | Send a blank email to php-smarty-dev+get-2911@lists.php.net to get a copy of this message | ||
False or null is fine with me. I am working on it and here is the problems I have found. I am trying to use the prev and next functions, these move the internal pointer on the array. They behave differently whether the array in the foreach is a reference or not:
$array = array( 'a' => 'a', 'b' => 'b', 'c' => 'c' );
$_from = $array;
foreach( $_from AS $key => $value ) {
$element = current($_from);
echo $element;
}
will print aaa, since the internal cursor of _from will not be moved and a will be the current one
where as:
$_from = &$array;
will print abc, b/c the internal cursor is moved
so for next and previous methods to work with smarty the _from assignment will have to be changed to reference ( & ) and we have to be careful not to move pointer ( php doesn't have method for 'peeking' ahead? )
prev($_from); // Rewind b/c current is really the next element
$previous = prev($_from); // This assigns previous
next($_from); // Now we are back to previous
next($_from); // Now we are back to current
$next = next($_from); // Get next
prev($_from); // move back to current
wow all that just to get the neighboring values, anyone know a better way?
Ken Snyder wrote:
Very interesting idea... You could do {assign var=previous_call value=$message.backtrace[$smarty.foreach.backtrace.index + 1]} but it wouldn't work for associative arrays or objects. I like it! What would be the desired behavior of $smarty.foreach.NAME.next when on the last item? A default value? NULL? --Ken Kerry Wilson wrote:-- Kerry Wilson Lead Developer Williams Web kwilson@wmsco.com | 423.485.4747I would like to enhance the foreach loop by adding next and previous to the foreach variables. Example usage: {foreach from=$message.backtrace item='call' name='backtrace'} {assign var='previous_call' value=|$smarty.foreach.backtrace.next}| <li style='list-style: none;'>{$call.file} [{$call.line}] - {$previous_call.class}.{$previous_call.function}(){/if}</li> {/foreach} In case you cannot tell I am using this to print a backtrace ( I want it to show the method it is currently in, not the one that it is calling ). Where does the foreach implementation reside in source? And is this a good thing to add to the base code?