Home >PHP Framework >ThinkPHP >Detailed explanation of two ways of looping in thinkphp6

Detailed explanation of two ways of looping in thinkphp6

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-03-30 17:01:435686browse

There are two tags in thinkphp6 that can realize array looping (volist tag and foreach tag). Let's follow the editor to see the use of these two tags.

Detailed explanation of two ways of looping in thinkphp6

First type: volist tag

Syntax:

{volist name="" id="" key="" offset="" length=""}
    循环体
{/volist}

Among them:

  • name: the variable name of the current template;

  • id: the current loop variable;

  • key: subscript, starting from 1 by default;

  • offset: the starting line number;

  • length: the obtained line number.

Example:

Define array:

<?php
namespace app\controller;
use think\facade\View;
class Test{
    public function index(){
        $arr=[
            [&#39;id&#39;=>1,&#39;name&#39;=>&#39;cmcc&#39;
            ],[&#39;id&#39;=>2,&#39;name&#39;=>&#39;cctv&#39;
            ],[&#39;id&#39;=>1,&#39;name&#39;=>&#39;cmqq&#39;
            ]
        ];
        view::assign(&#39;arr&#39;,$arr);
        return view::fetch();
    }
}
?>

Traverse in template:

{volist name="arr" id="vv" key="kk" offset="1" length="1"}
    <div>
        {$kk} --- {$vv[&#39;name&#39;]}
    </div>
    {/volist}

Output result:

Detailed explanation of two ways of looping in thinkphp6

We set the interception to start from 1 and intercept one, so the output result is cctv.

Second type: foreach tag

Syntax:

{foreach $name as $key=>$id}
        循环体
    {/foreach}

Among them:

  • ## name: variable name of the current template;

  • id: current loop variable;

  • key: subscript, starting from 0 by default.

Example: The definition array of

foreach is the same as that of volist, so we won’t write it here anymore, we will directly Look at the traversal in the template.

{foreach $arr as $k=>$v}
        <div>
            {$k} --- {$v[&#39;name&#39;]}
        </div>
    {/foreach}

The output result is:


Detailed explanation of two ways of looping in thinkphp6

We can see that the foreach tag needs to be added when looping. #$ (dollar sign), and the volist tag does not need to be added with $ (dollar sign) when recycling.

Recommended learning:

thinkphp6 video tutorial

The latest 10 thinkphp video tutorials

The above is the detailed content of Detailed explanation of two ways of looping in thinkphp6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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