smarty模板引擎使用內建函數foreach迴圈取出所有數組值的方法_php執行個體

來源:互聯網
上載者:User
本文執行個體講述了smarty內建函數foreach的使用方法,分享給大家供大家參考。具體如下:

顯示檔案:index.php:
複製代碼 代碼如下:<?php
//建立smarty對象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();

$arr1 = array("北京","上海","廣州");//索引數組
$smarty->assign("arr1",$arr1);//分配索引數組
$arr2 = array("city1"=>"北京","city2"=>"上海","city3"=>"廣州");//關聯陣列
$smarty->assign("arr2",$arr2);//分配關聯陣列
$arr3 = array(array("北京","上海","廣州"),array("關羽","張飛","美女"));//二維索引數組
$smarty->assign("arr3",$arr3);
$arr4 = array(array("c1"=>"北京","c2"=>"上海","c3"=>"廣州"),array("n1"=>"關羽","n2"=>"張飛","n3"=>"美女"));//二維關聯陣列
$smarty->assign("arr4",$arr4);

$smarty->display("temp.tpl");
?>

模板檔案:temp.tpl
複製代碼 代碼如下:

smarty內建函數foreach,迴圈取出數組值


執行個體1:一維索引數組


{foreach from=$arr1 item=temp}
{$temp}
{/foreach}

執行個體2:一維關聯陣列——>item為索引值,key為鍵名。如果不取key,取出方法與一維索引數組相同,當然索引數組也是有key的0,1,2...


{foreach from=$arr2 item=temp key=k}
{$k}={$temp}
{/foreach}

執行個體3:二維索引數組——>兩次迴圈即可


{foreach from=$arr3 item=temp}
{foreach from=$temp item=value}
{$value}
{/foreach}

{/foreach}

執行個體4:二維關聯陣列——>同樣兩次迴圈即可


{foreach from=$arr4 item=temp}
{foreach from=$temp item=value key=k}
{$k}={$value}
{/foreach}

{/foreach}

希望本文所述對大家的php程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.