


PHP template engine Smarty built-in function foreach, foreachelse usage analysis, smartyforeachelse_PHP tutorial
Jul 12, 2016 am 08:54 AMUsage analysis of PHP template engine Smarty's built-in functions foreach and foreachelse, smartyforeachelse
This article describes the usage of PHP template engine Smarty's built-in functions foreach and foreachelse. Share it with everyone for your reference, the details are as follows:
In Smarty templates, you can use foreach to repeat a block. In the template, an array needs to be allocated from PHP. This array can be a multidimensional array. The {foreach} tag in Smarty is the same as the foreach in PHP, except that one of them is used in the template file and the other is used in the PHP script. Therefore, the syntax will be different. However, they all do the same thing, which is to iterate over the contents of an array. There is also a {foreachelse} tag opposite to the {foreach} tag. The function of the {foreachelse} tag is: if the array is empty, then the content in the tag is executed. {foreach} and {/foreach} must appear in pairs in the template. It has four parameters, of which two parameters from and item are necessary. Please see the list below for its parameters:
property | Type | Is it necessary | Default value | Description | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from | string | Yes | n/a | Name of the array to be looped | |||||||||||||||||||||||||
item | string | Yes | n/a | Variable name of the currently processed element | |||||||||||||||||||||||||
key | string | No | n/a |
Key name of the currently processed element
|
|||||||||||||||||||||||||
name | string | No | n/a | The name of the loop, used to access the loop |
We use an example to demonstrate the use of {foreach} and {foreachelse} in Smarty.
Example idea: retrieve the content from the database, assign it to an array variable $_html, then assign this array variable to the template, and then traverse the array in the template
test.sql (SQL data used)
-- -- 表的結(jié)構(gòu) `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` mediumint(8) unsigned NOT NULL auto_increment, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `addTime` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; -- -- 轉(zhuǎn)存表中的數(shù)據(jù) `user` -- INSERT INTO `user` (`id`, `username`, `email`, `addTime`) VALUES (1, '蒼井空', 'canjingkong@sina.com.cn', '2011-10-24 00:00:00'), (2, '櫻木花道', 'ymhd@163.com', '2011-10-24 00:00:00'), (3, '赤木晴子', 'chimiqingzi@yahoo.com,cn', '2011-10-24 00:00:00'), (4, '流川楓', 'lcfeng@sina.com', '0000-00-00 00:00:00'), (5, '蠟筆小新', 'labixiaoxin@sina.com', '2011-10-24 00:00:00'), (6, '金剛葫蘆娃', 'jghlw@sina.com', '2011-10-24 00:00:00');
init.inc.php (template initialization file)
<?php define('ROOT_PATH', dirname(__FILE__)); //設(shè)置網(wǎng)站根目錄 require ROOT_PATH.'/libs/Smarty.class.php'; //加載 Smarty 模板引擎 $_tpl = new Smarty(); //創(chuàng)建一個(gè)實(shí)例對(duì)象 $_tpl->template_dir = ROOT_PATH.'/tpl/'; //重新指定模板目錄 $_tpl->compile_dir = ROOT_PATH.'./com/'; //重新指定編譯目錄 $_tpl->left_delimiter = '<{'; //重新指定左定界符 $_tpl->right_delimiter = '}>'; //重新指定右定界符 ?>
index.php (main file)
<?php require 'init.inc.php'; //引入模板初始化文件 global $_tpl; $_mysqli = new mysqli(); //創(chuàng)建一個(gè) mysqli() 對(duì)象 $_mysqli->connect('localhost','root','數(shù)據(jù)庫(kù)密碼','數(shù)據(jù)庫(kù)名'); //連接數(shù)據(jù)庫(kù),請(qǐng)您自行設(shè)置 $_mysqli->set_charset('utf8'); //設(shè)置編碼 $_result = $_mysqli->query("select username,email,addTime from user order by id asc"); $_html = array(); while (!!$_row=$_result->fetch_assoc()) { $_html[] = $_row; } $_tpl->assign('data',$_html); //把數(shù)組分配到模板中 $_tpl->display('index.tpl'); //引入模板 $_mysqli->close(); //關(guān)閉數(shù)據(jù)庫(kù),釋放資源 ?>
tpl/index.tpl (template file of the main file index.php)
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>foreach,foreachelse</title> </head> <body> <table align="center" border="1" width="800"> <{foreach from=$data item="row" name="ls"}> <!-- 這個(gè)foreach 循環(huán)分配過(guò)來(lái)的數(shù)組有幾行數(shù)據(jù) --> <!-- 在此,我們做幾個(gè)保留變量 $smarty.foreach 的操作 --> <!-- 當(dāng)數(shù)據(jù)顯示第一條的時(shí)候,第一行的表格背景為黃色,使用屬性:first --> <!-- 當(dāng)數(shù)據(jù)顯示最后一條的時(shí)候,最后一行的表格背景為藍(lán)色,使用屬性:last --> <!-- 顯示下分配過(guò)來(lái)的數(shù)組的總個(gè)數(shù),使用屬性:total --> <{if $smarty.foreach.ls.first}> <tr bgcolor="#FFFF00"> <!-- 第一行背景為黃色 --> <{elseif $smarty.foreach.ls.last}> <tr bgcolor="#0000FF"> <!-- 最后一行背景為藍(lán)色 --> <{else}> <tr> <{/if}> <td><{$smarty.foreach.ls.iteration}></td><!-- 注意:這里是保留變量 $smarty.foreach 的使用,iteration:總是從 1 開(kāi)始,每執(zhí)行一次增加 1 --> <{foreach from=$row item="col" name="lsin"}> <!-- 這個(gè)foreach 循環(huán)數(shù)組內(nèi)的內(nèi)容,顯示在表格的<td></td>標(biāo)簽里 --> <td><{$col}></td> <{/foreach}> </tr> <{foreachelse}> <!-- 如果分配過(guò)來(lái)的數(shù)組中沒(méi)有數(shù)據(jù),那么就執(zhí)行下面的操作! --> <tr> <td>對(duì)不起!暫時(shí)沒(méi)有數(shù)據(jù)。</td> </tr> <{/foreach}> <tr> <td colspan="4" align="center">分配數(shù)組的總記錄數(shù)為:<{$smarty.foreach.ls.total}>條</td> </tr> </table> </body> </html>
Execution result:
Finally, the array $_html passed in the main file index.php is a two-dimensional array. The use of reserved variables $smarty.foreach is based on the name attribute in the {foreach} tag. The reserved variable attributes used are: first (first record), last (last record), iteration (always starts from 1, Increase by 1 for each execution), total (used to display the number of loop executions)
Readers who are interested in more PHP-related content can check out the special topics of this site: "Basic Tutorial for Getting Started with Smarty Templates", "Summary of PHP Template Technology", "Summary of PHP Database Operation Skills Based on PDO", "PHP Operations and Operators" Usage summary", "PHP network programming skills summary", "PHP basic syntax introductory tutorial", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "Summary of Common Database Operation Skills in PHP"
I hope this article will be helpful to everyone’s PHP program design based on smarty templates.
Articles you may be interested in:
- Detailed explanation of the built-in functions of PHP template engine Smarty
- Detailed explanation of the usage of the built-in variable mediator of PHP template engine Smarty
- PHP Usage of custom variable mediator in template engine Smarty
- Analysis of usage of reserved variables in PHP template engine Smarty
- Example of how to use the configuration file of PHP template engine Smarty in template variables
- Examples of how to use variables in PHP template engine Smarty
- How smarty template engine gets data from php
- ThinkPHP How to use smarty template engine
- In PHP template Detailed explanation of the random number generation method and math function of engine smarty
- Summary of cache usage of PHP template engine Smarty
- 6 tips of php smarty template engine
- [PHP] template An in-depth and simple introduction to the engine Smarty
- Detailed explanation of the usage of the built-in functions section and sectionelse of the PHP template engine Smarty

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
