Blogger Information
Blog 38
fans 0
comment 0
visits 29613
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0417,for(),while(),foreach()循环读取数组
riskcn的博客
Original
641 people have browsed it

重点:

数组循环在开发中使用很广,重点研究

要熟练掌握键和值的关系,对同一数组循环操作后记得初始化指针

foreach()循环自动调整指针位置,for()和while()循环需要在每次循环前移动指针到下一位

实例

<?php 
header("Content-type: text/html; charset=utf-8");//声明编码,防止中文乱码 
// 创建一个人物信息数组
$user=['id'=>1205,'name'=>'老王','sex'=>'男','age'=>50,'国籍'=>'中国','婚姻状况'=>'已婚'];
echo ("<pre>");//格式化输出
print_r($user);//打印数组
echo('<hr color="red">');
// echo count($user);
// for()循环1,表头先画出来循环值
echo ('<h2>一、for()循环</h2>');
echo ('<table cellspacing="0" cellpadding="5" border="1"><caption><h3>人员信息表</h3></caption><tr bgcolor="lightgreen"><th>ID</th><th>姓名</th><th>性别</th><th>年龄</th><th>国籍</th><th>婚姻状况</th></tr><tr align="center">');
for($i=0;$i<count($user);$i++){
	echo ('<td>'.current($user));
	next($user);//循环过程需将指针下移
	echo ('</td>');
};
echo ('</tr></table>');


echo ('<hr>');
reset($user);

//for()循环2,两次循环使用键名做表头
echo ('<table cellspacing="0" cellpadding="5" border="1"><caption><h3>人员信息表</h3></caption><tr bgcolor="lightgreen">');

for($i=0;$i<count($user);$i++){
	echo ('<th>'.key($user));
	next($user);
	echo ('</th>');
};
echo ('</tr>');
reset($user);
echo ('<tr align="center">');
for($i=0;$i<count($user);$i++){
	echo ('<td>');
	echo current($user);
	next($user);
	echo ('</td>');
};
echo ('</tr></table>');

reset($user);
echo('<hr color="red">');
// while()循环1
echo ('<h2>二、while()循环</h2>');

echo ('<table cellspacing="0" cellpadding="5" border="1"><caption><h3>人员信息表</h3></caption><tr bgcolor="lightgreen"><th>ID</th><th>姓名</th><th>性别</th><th>年龄</th><th>国籍</th><th>婚姻状况</th></tr><tr align="center">');
$i=0;
while($i<count($user)){
	echo ('<td>'.current($user));
	next($user);
	echo ('</td>');
	$i++;
}
echo ('</tr></table>');

reset($user);
echo('<hr color="red">');
// foreach()循环
echo ('<h2>三、foreach()循环</h2>');
echo ('<table cellspacing="0" cellpadding="5" border="1"><caption><h3>人员信息表</h3></caption></caption><tr bgcolor="lightgreen"><th>ID</th><th>姓名</th><th>性别</th><th>年龄</th><th>国籍</th><th>婚姻状况</th></tr><tr align="center">');
	foreach ($user as $value) {	
		echo ('<td>');
		echo $value;
		echo ('</td>');	
	}
echo ('</tr></table>');	

运行实例 »

点击 "运行实例" 按钮查看在线实例

QQ截图20180418160633.png

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post