Home > Backend Development > PHP Tutorial > thinkphp模板中怎么循环遍历数组

thinkphp模板中怎么循环遍历数组

PHPz
Release: 2020-09-05 13:13:50
Original
3765 people have browsed it

thinkphp模板中循环遍历数组的方法:可以利用volist标签和foreach标签来实现,具体语法为:【循环体循环体】。

thinkphp模板中怎么循环遍历数组

thinkphp模板中怎么循环遍历数组?

在TP中系统提供了2个标签来实现数组在模板中的遍历:volist标签和foreach标签

volist 语法

<volist name="需要遍历的模板变量" id="当前遍历到的元素">
  循环体
</volist>
Copy after login

在PHP中foreach($variable as $value){ 循环体}

TP中

<foreach name="需要遍历的模板变量" item="当前遍历到的元素">
 循环体
</foreach>
Copy after login

两个遍历模板标签大致一样,volist除了name,id外还支持mod,key,length等等

foreach除了name,item外只支持key属性

示例:

定义数组:

<?php
namespace Admin\Controller;
use Think\Controller;
class TestController extends Controller { 
public function test11(){
        //一维数组
        $array=array(&#39;西游记&#39;,&#39;水浒传&#39;,&#39;红楼梦&#39;,&#39;三国演义&#39;);
        //二维数组
        $array2=array(
            array(&#39;孙悟空&#39;,&#39;猪八戒&#39;,&#39;沙僧&#39;,&#39;小白龙&#39;),
            array(&#39;悟空&#39;,&#39;八戒&#39;,&#39;沙僧&#39;,&#39;小白龙&#39;),
            array(&#39;大圣&#39;,&#39;八戒&#39;,&#39;沙僧&#39;,&#39;小白龙&#39;),
            array(&#39;孙悟空&#39;,&#39;猪八戒&#39;,&#39;沙和尚&#39;,&#39;白龙&#39;),
        );
        //变量分配
        $this->assign(&#39;array&#39;,$array);
        $this->assign(&#39;array2&#39;,$array2);
        //模板常量展示
        $this->display();
    }
}
Copy after login

在模板中遍历

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
//遍历一维数组
volist标签:<br>
<volist name="array" id="vol">
    {$vol}-
</volist>
<hr>
foreach标签:<br>
<foreach name="array" item="for">
    {$for}-
</foreach>
<hr>
<hr>
//遍历二维数组
volist标签:<br>
<volist name="array2" id="vol">
   <volist name="vol" id="vo">
       {$vo}-
   </volist>
    <br>
</volist>
<hr>
foreach标签:<br>
<foreach name="array2" item="for">
    {$for[0]}- {$for[1]}- {$for[2]}- {$for[3]}<br>
</foreach>
</body>
</html>
Copy after login

1.png

2.png

更多相关知识,请访问 PHP中文网!!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template