作业效果
实例
<meta charset="UTF-8"> <!DOCTYPE html> <html lang="en"> <head> <title>For(), while(),foreach(),实现索引数组,关联数组的遍历</title> <style type="text/css"> h3,h4 { text-align: center; } .box1 { text-align: center; } .box2 { text-align: center; } .box3 { text-align: center; } table { margin: auto; } caption { font-size: 2em; color: red } th { color: green; } td { color:fuchsia; font-size: 1.2em; } </style> </head> <body> <?php echo '<h3 style="color:green"> For(), while(),foreach(),实现索引数组,关联数组的遍历</h3><hr color="green">'; /* * 数组遍历 * 1. foreach($arr as $key => $value) {} * 2. 原理:将数组$arr按键值对方式依次取出到$key=>$value中,逐个处理,类似于回调 * 3. 如果只对值处理,可以省略$key: foreach($arr as $value) {} * 4. 特殊适合关联数组,当然也适用于索引数组 */ $color = ['red'=>'红', 'orenge'=>'橙', 'yellow'=>'黄', 'green'=>'绿', 'cyan'=>'青', 'blue'=>'蓝' ,'purple'=>'紫']; echo '<div class=box1>'; ///////用for循环来实现关联数组的遍历//////// /// /// echo '<h3 style="color:green">用for来实现循环遍历</h3>'; for ($i=0; $i<count($color); $i++) { echo key($color),'(',current($color),')','<br>'; next($color); } echo '</div>'; echo '<hr color="red">'; //////////用while循环来实现////////////////// echo '<div class=box2>'; echo '<h3 style="color:green">用while来实现循环遍历</h3>'; reset($color); $i = 0; while ($i<count($color)) { echo key($color),'=>',current($color),'<br>'; next($color); $i++; } echo '</div>'; echo '<hr color="red">'; /////////foreach($arr as $key=>$value):数组专用的遍历语法结构/////// echo '<div class=box3>'; echo '<h3 style="color:green">用foreach($arr as $key=>$value):数组专用的遍历语法结构</h3>'; echo '<h4>彩虹的颜色</h4>'; echo '<ul>'; foreach ($color as $key => $value) { echo '<li>'.$key.':'.$value.'</li>'; } echo '</ul>'; echo '</div>'; echo '<hr color="red">'; ///////////如果只对值感兴趣/////// echo '<table border="1" cellpadding="3" cellspacing="0" width="300">'; echo '<caption>彩虹颜色</caption>'; echo'<tr>'; foreach ($color as $key => $value) { echo '<th align="center">'.$key.'</th>'; } echo '</tr>'; echo '<tr>'; foreach ($color as $key => $value) { echo '<td align="center">'.$value.'</td>'; } echo '</tr>'; echo '</table>'; echo '<hr color="red">'; ?> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
手抄作业