* 陣列遍歷
* 1. foreach($arr as $key => $value) {}
* 2. 原理:將陣列$arr按鍵值對方式依序取出到$key=>$value中,逐一處理,類似回呼
* 3. 如果只對值處理,可以省略$key: foreach($arr as $value) {}
* 4. 特殊適合關聯數組,當然也適用於索引數組
$teacher = ['id'=>1001, 'name'=>'peter zhu', 'salary'=> 3000, 'course'=>'php'];
//用for循環來實現關聯數組的遍歷
for ($i=0; $i<count($teacher); $i++) { echo key($teacher),'=>',current($teacher),'<br>'; next($teacher); } echo '<hr color="red">';
//用while循環來實現
reset($teacher); $i = 0; while ($i<count($teacher)) { echo key($teacher),'=>',current($teacher),'<br>'; next($teacher); $i++; } echo '<hr color="red">'; //foreach($arr as $key=>$value):数组专用的遍历语法结构 echo '<h4>讲师信息</h4>'; echo '<ul>'; foreach ($teacher as $key => $value) { echo '<li>'.$key.':'.$value.'</li>'; } echo '</ul>'; echo '<hr color="red">'; //如果只对值感兴趣 echo '<table border="1" cellpadding="3" cellspacing="0" width="300">'; echo '<caption>讲师信息表</caption>'; echo '<tr bgcolor="lightskyblue"><th>ID</th><th>姓名</th><th>工资</th><th>课程</th></tr>'; echo '<tr>'; foreach ($teacher as $value) { echo '<td align="center">'.$value.'</td>'; } echo '</tr>'; echo '</table>'; echo '<hr color="red">';
//建立一個日期選擇器
echo '
選擇你的生日:
';//生成年份
$years = range(1980, 2000); echo '<select name="year">'; foreach ($years as $value) { echo '<option>'.$value.'年</option>'; } echo '</select>'; echo ' ';
//生成月
$months = range(1, 12); echo '<select name="months">'; foreach ($months as $value) { echo '<option value='.$value.'>'.sprintf("%02d",$value) .'月</option>'; } echo '</select>'; echo ' ';
//生成日
$days = range(1, 31); echo '<select name="days">'; foreach ($days as $value) { echo '<option value='.$value.'>'.sprintf("%02d",$value) .'日</option>'; } echo '</select>'; echo ' '; echo '<button>提交</button>';