Home > Article > PHP Framework > Two methods of loop traversal in ThinkPHP (volist and foreach tags)
In ThinkPHP, the system provides two tags to facilitate operations: the volist tag and the foreach tag.
volist syntax format:
<volist name='需要遍历的模板变量名' id='当前遍历到的元素名' 循环体 </volist>
Note: volist is a double-label statement and needs to be closed.
foreach syntax format:
<foreach name='需要遍历的模板变量名' item='当前遍历到的元素名' 循环体 </foreach>
Note:
foreach is also a double-label statement and needs to be closed.
Difference:
The volist syntax format is roughly the same as the foreach syntax format. In addition to the above name and id attribute pairs, volist also supports more attributes. Yes, such as mod, key, length, etc., and the foreach tag only supports key attribute pairs in addition to the above name and item. It can be understood that the foreach tag is a simplified version of the volist tag.
It is recommended to use the volist tag as much as possible in actual operations.
Case 1:
Traversal of one-dimensional array
<?php ...//创建控制器TestController省略 public function test(){ $array = array('西游记','红楼梦','三国演义','水浒传'); $array2 = array( array('孙悟空','猪八戒','沙和尚','唐僧'), array('贾宝玉','薛宝钗','刘姥姥','林黛玉'), array('刘备','关羽','张飞','曹操'), array('宋江','林冲','鲁智深','时迁') ); $this -> assign('array',$array); $this -> display(); } <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <volist name='array' id='vol'> {$vol} - </volist><hr/> <foreach name='array' item='for'> {$for} - </foreach> </body> </html>
Output display:
Case 2:
Traversal of two-dimensional array
<?php ...创建TestController控制器 public function test(){ $array = array('西游记','红楼梦','三国演义','水浒传'); $array2 = array( array('孙悟空','猪八戒','沙和尚','唐僧'), array('贾宝玉','薛宝钗','刘姥姥','林黛玉'), array('刘备','关羽','张飞','曹操'), array('宋江','林冲','鲁智深','时迁') ); $this -> assign('array',$array); $this -> assign('array2',$array2); $this -> display(); }
<!DOCTYPE html> <html> <head> <title>test</title> </head> <body> /*volist循环遍历,嵌套循环*/ <volist name='array2' id='vol'> <volist name='vol' id='vo'> {$vo}- </volist><br/> </volist><hr/> /*foreach循环遍历,嵌套循环*/ <foreach name='array2' item='for'> <foreach name='for' item='fo'> {$fo}- </foreach><br/> </foreach> </body> </html>
Output display:
More related ThinkPHP For knowledge, please visit ThinkPHP Tutorial!
The above is the detailed content of Two methods of loop traversal in ThinkPHP (volist and foreach tags). For more information, please follow other related articles on the PHP Chinese website!