Smarty 模板中的foreach函数遍历多维数组
Smarty 模板中的foreach函数遍历多维数组
数据库'ye'中的用户表'user'
users;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | MUL | NULL | |
| password | varchar(32) | NO | | NULL | |
| phone | varchar(20) | YES | MUL | | |
+----------+-------------+------+-----+---------+----------------+
表中的数据
mysql> select * from users;
+----+----------+----------------------------------+-------------+
| id | username | password | phone |
+----+----------+----------------------------------+-------------+
| 1 | admin | 81dc9bdb52d04dc20036dbd8313ed055 | 13590209116 |
| 2 | user | 81dc9bdb52d04dc20036dbd8313ed055 | |
| 10 | liming | bc6a4e700fca7eb9615d8fa1e111ffdf | 2147483647 |
| 7 | users | b3af409bb8423187c75e6c7f5b683908 | 1234 |
| 11 | Kitty | c4ca4238a0b923820dcc509a6f75849b | 1 |
| 12 | Bob | c81e728d9d4c2f636f067f89cc14862c | 2 |
| 13 | Tony | c4ca4238a0b923820dcc509a6f75849b | 1 |
| 14 | Jenny | c81e728d9d4c2f636f067f89cc14862c | 2 |
+----+----------+----------------------------------+-------------+
index0.php
<?php /* 第一步:加载自定义的Smarty初使化文件 */
require "init.inc.php";
$con=mysql_connect('localhost','root','1234');
if(!$con)
die('数据库连接失败'.mysql_error());
mysql_select_db('ye',$con) or die('不能连接数据库:'.mysql_error());
$sql='select id,username,password,phone from users';
$result=mysql_query($sql);
while($u=mysql_fetch_row($result))
$user[]=$u;
/*foreach($user as $row)
{
foreach($row as $col)
echo $col." ";
echo'<br>';
}*/
$smarty->assign('user',$user);
$smarty->display("test0.html");
?>
test0.html
<!DOCHTML>
<html>
<head>
<meta charset="utf-8">
<title>Smarty 初体验</title>
</head>
<body>
<table border="1" width="800" align="center">
<caption>
<h1>USERS</h1>
</caption>
<tr>
<th>@index</th>
<th>@iteration</th>
<th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Phone</th>
</tr>
<{*遍历数组$user,将数据表数组$user每行数据赋值给$row*}>
<{foreach from=$user item=$row}>
<!---->
<{if $row@first}>
<tr bgcolor="yellow"> <{elseif $row@last}>
<tr bgcolor="blue"> <{elseif $row@index is even}>
<tr bgcolor=#cccccc"> <{else}>
<tr> <{/if}>
<td><{$row@index}></td>
<td><{$row@iteration}></td>
<{*双层foreach嵌套遍历每行数据*}>
<{foreach from=$row item=$col}>
<td><{$col}></td>
<{/foreach}> </tr>
<{/foreach}>
<{*使用@show判断{foreach}循环是否无数据显示*}>
<{if $row@show}>
<tr>
<td colspan="6" align="center">没数据了/(ㄒoㄒ)/~~</td>
</tr>
<{/if}>
</table>
循环共<{$row@total}>次<br>
<!--<{print_r($user)}>-->
</body>
</html>