Smarty foreach Detailed description _php tutorial

Source: Internet
Author: User
Tags php foreach smarty template

Smarty foreach Detailed description


For the knowledge of Smarty foreach, here is a detailed explanation of its function and usage.

Smarty {foreach} is used to iterate through an associative array like iterating over a numeric index array, unlike {section}, which can only access a numeric index array, the syntax of {foreach} is much simpler than the syntax of {section}. But as a compromise, it can only be used for a single array. Each {foreach} token must appear paired with the close tag {/foreach}.

Smarty foreach has the following properties:

Property name Type Types Required Necessary Default Defaults Description Description
From Array arrays Yes necessary N/A Iterating through an array
Item String strings Yes necessary N/A The variable name of the current element
Key String strings No optional N/A Variable name of the current key name
Name string character No optional N/A The name of the Foreach loop used to access the Foreach property

foreach is another scenario for processing loops other than section (choose a different scenario depending on your needs).

foreach is used to work with simple arrays (the same type of elements in an array), which is much simpler to format than the section, with the drawback that only simple arrays can be processed.

foreach must be paired with/foreach and must specify the From and item properties.

The Name property can be arbitrarily specified (a combination of letters, numbers, and underscores).

The name of the {foreach} loop can be any combination of letters, arrays, underscores, and references to PHP variables.

{foreach} loops can be nested, and the names of nested {foreach} should differ.

The From property is usually an array of values and is used to determine the number of cycles of {foreach}.

{Foreachelse} will be executed when there is no value in the from variable.

The {foreach} loop also has a variable of its own property, which can be accessed through {$smarty. Foreach.name.property}, where "name" is the Name property.

Note: The Name property is only valid when the {foreach} property needs to be accessed, unlike {section}. Accessing a {foreach} property that does not have a name defined does not throw an error, but will result in unpredictable results.

Smarty {foreach} has several properties that are non-parametric in addition to the attributes that are parameters: index, iteration, first, last, show, Total, below one by one description:

Property name Description Description
Index Index value used to access the current foreach, index always starts at 0
Iteration

Iteration is used to show the number of executions of the current loop, iteration always starts at 1 and increases by 1 per execution

First First is set to True when the current foreach loop executes
Last Last is set to True when the current foreach Loop executes to the final pass
Show show is a parameter to foreach. Evaluates to a Boolean value of TRUE or false. If the loop is not displayed if it is specified as false, if the loop specifies a foreachelse clause, the clause is also displayed depending on the value of the show
Total Total is used to show the number of times a loop is executed and can be called after a loop or loop execution

Here are a few examples to illustrate the use of Smarty foreach properties:

(1) Demo Item and key property

$arr = Array (9 = ' tennis ', 3 = ' swimming ', 8 = ' Coding ');
$smarty->assign (' MyArray ', $arr);
?>

Output $myarray in the form of a template key name/key-value pair, similar to the PHP foreach.


      {foreach from= $myArray key=k item=v}
    • {$k}: {$v}

    • {/foreach}


The example above will output:


    • 9:tennis

    • 3:swimming

    • 8:coding

(2) When the Item property of foreach is an associative array

$items _list = Array (
A. Array (' no ' + = 2456, ' label ' = ' salad '),
+ = Array (' no ' = = 4889, ' label ' = ' Cream ')
);
$smarty->assign (' Items ', $items _list);
?>

In the template, the URL is output through $myid $items


      {foreach from= $items Key=myid item=i}
    • {$i. No}: {$i. Label}

    • {/foreach}


The example above will output:


    • 2456:salad

    • 4889:cream

(3) foreach uses nested item and key

Sets an array to smarty, including the key for Each loop value corresponding to each key name.

$smarty->assign (' Contacts ', array (
Array (' phone ' = ' 1 ',
' Fax ' = ' 2 ',
' Cell ' = ' 3 '),
Array (' phone ' = ' 555-4444 ',
' Fax ' = ' 555-3333 ',
' Cell ' = ' 760-1234 ')
));
?>

The template used to output the $contact.

{foreach Name=outer item=contact from= $contacts}


{foreach Key=key item=item from= $contact}
{$key}: {$item}

{/foreach}
{/foreach}

The example above will output:


Phone:1

Fax:2

Cell:3


phone:555-4444

fax:555-3333

cell:760-1234


(4) Smarty foreach Index property usage

{* Output one header chunk per five lines *}








{foreach from= $items key=myid item=i Name=foo} {if $smarty. foreach.foo.index% 5 = = 0} {/if} {/foreach}
Title
{$i. Label}

(5) Smarty foreach iteration attribute usage

{* This example will output 0|1, 1|2, 2|3, ... Wait *}
{foreach from= $myArray item=i Name=foo}
{$smarty. foreach.foo.index}| {$smarty. Foreach.foo.iteration},
{/foreach}

(6) smarty foreach First attribute usage

{* Show latest instead of ID *} for the first entry








{foreach from= $items key=myid item=i Name=foo} {/foreach}
{if $smarty. Foreach.foo.first} latest{else}{$myId}{/if} {$i. Label}

(7) smarty foreach last attribute usage

{* Add a horizontal marker at the end of the list *})
{foreach from= $items key=part_id item=prod name=products}
{$prod} {if $smarty. Foreach.products.last} {else},{/if}
{Foreachelse}
... content ...
{/foreach}

(8) Smarty foreach Show property usage

Show is a parameter of {foreach}. Show is a Boolean value. If the value is False,{foreach} will not be displayed. If there is a corresponding {foreachelse}, it will be displayed.

(9) Smarty foreach Total attribute usage

{* Show lines at end of position *}
{foreach from= $items key=part_id item=prod Name=foo}
{$prod .name>


{if $smarty. Foreach.foo.last}
{$smarty. foreach.foo.total} items
{/if}
{Foreachelse}
... something else ...
{/foreach}

Ok, about Smarty foreach summed up so much, more about smarty knowledge, please refer to this site: Smarty knowledge Topic

Articles you may be interested in

    • Array_walk and foreach, for efficiency comparisons, PHP performance optimizations
    • Comparison of performance when using In_array () foreach Array_search () to find out if an array is included
    • Smarty extension for loop in template
    • Smarty include file methods for using variables
    • PHP finds whether a value exists in the array (In_array (), Array_search (), array_key_exists ())
    • Use PHP functions in Smarty Templates and how to use multiple functions for a variable in a smarty template
    • The difference and usage of SELECT into from and insert into select
    • Fatal error Class ' ziparchive ' not found ... The solution

http://www.bkjia.com/PHPjc/976850.html www.bkjia.com true http://www.bkjia.com/PHPjc/976850.html techarticle Smarty foreach details the knowledge about Smarty foreach, and here is a detailed explanation of its role and usage. Smarty {foreach} is used like iterating over a numeric index array ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.