smarty foreach section 高级应用

本文展示了一个使用Smarty模板引擎结合PHP进行数据库操作的例子。通过PDO连接本地MySQL数据库,并从两个不同的表中获取数据,再将这些数据组织成嵌套结构显示在HTML页面上。示例中使用了foreach循环来遍历数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?
include_once("config.php");
$pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
$sql = "select * from wap_3g_01";
$result = $pdo->query($sql);
$info1 = $result->fetchAll();
$sql = "select * from wap_3g_02";
$result = $pdo->query($sql);
while ($row = $result->fetch()){
    $info2[$row['typeid']][] = $row;
}
$smarty->assign('info1',$info1);
$smarty->assign('info2',$info2);
$smarty->display('test.tpl');
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>smarty-test</title>
</head>

<body >
<form name="myform" id="myform"  method="post" action="">
  {|foreach from=$info1 item=info key=key|}
    第一层:{|$info.id|}
    <br/>
     {|foreach from=$info2[$info.id] item=infos key=key|}
      
          第二层:{|$infos.id|}
          <br/>
     {|/foreach|}
     <br/> 
    
  {|/foreach|}
 
   <br/>

   {|foreach from=$info1 item=info key=key|}
  
    第一层:{|$info.id|}
    <br/>
     {|section name='se' loop=$info2[$info.id] start=0 step=1|}
     
        第二层:{|$info2[$info.id][se].id|}      
        <br/>
      {|/section|}
    <br/>      
   
   {|/foreach|}
</form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值