首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 區塊巢狀迴圈:section 嵌套輸出多層資料結構

     編輯:PHP 綜合知識

應用場景

電商分類頁:大分類 → 小分類 → 商品列表 三層結構,需在模板中逐層迴圈輸出。

資料結構範例

$typeList = [
    [
        'typeName' => '手機通訊',
        'shop' => [
            ['id'=>1, 'name'=>'iPhone 15', 'price'=>30000, 'num'=>10, 'img_url'=>'/img/iphone.jpg'],
            ['id'=>2, 'name'=>'Samsung S24', 'price'=>28000, 'num'=>5, 'img_url'=>'/img/samsung.jpg'],
        ]
    ],
    [
        'typeName' => '電腦辦公',
        'shop' => [
            ['id'=>3, 'name'=>'MacBook Pro', 'price'=>60000, 'num'=>3, 'img_url'=>'/img/macbook.jpg'],
        ]
    ]
];
$smarty->assign('typeList', $typeList);

模板完整寫法

{section name=sec1 loop=$typeList}
    <table class="category-header">
        <tr>
            <td><strong>{$typeList[sec1].typeName}</strong></td>
            <td><a href="more.html">更多</a></td>
        </tr>
    </table>

    <table class="product-grid">
        <tr>
        {section name=sec2 loop=$typeList[sec1].shop}
            <td>
                <a href="product.php?id={$typeList[sec1].shop[sec2].id}">
                    <img src="{$typeList[sec1].shop[sec2].img_url}" width="84" height="88">
                </a>
                <br>
                <a href="product.php?id={$typeList[sec1].shop[sec2].id}">
                    {$typeList[sec1].shop[sec2].name}
                </a>
                <br>數量:{$typeList[sec1].shop[sec2].num}
                <br>價格:{$typeList[sec1].shop[sec2].price} 元
            </td>
        {/section}
        </tr>
    </table>
{/section}

關鍵語法解析

語法說明
{section name=sec1 loop=$typeList}外層迴圈,索引變數 sec1
$typeList[sec1].shop存取外層當前項目的 shop 子陣列
{section name=sec2 loop=$typeList[sec1].shop}內層迴圈,索引變數 sec2,循環來源為動態子陣列
$typeList[sec1].shop[sec2].id雙重索引存取孫層屬性

進階技巧:迴圈屬性存取

{section name=sec1 loop=$typeList}
    {$smarty.section.sec1.index}    {* 0-based 索引 *}
    {$smarty.section.sec1.iteration} {* 1-based 迴圈次數 *}
    {$smarty.section.sec1.first}     {* 是否第一筆 *}
    {$smarty.section.sec1.last}      {* 是否最後一筆 *}
    {section name=sec2 loop=$typeList[sec1].shop}
        {$smarty.section.sec2.index}
    {/section}
{/section}

常見錯誤與除錯

  • 子陣列鍵名不存在: 確認 PHP 端 $typeList[$i]['shop'] 確實存在且為陣列。
  • 變數名稱衝突: 巢狀迴圈索引名不可相同(sec1/sec2)。
  • 輸出空白: 若子陣列為空,內層 section 直接不輸出,可搭配 {$typeList[sec1].shop|@count} 判斷顯示「無商品」。

相關專題推薦

  • 《Smarty 模板入門基礎教程》
  • 《PHP 模板技術總結》
  • 《PHP 陣列(Array)操作技巧大全》
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved