for(),while(),foreach()实现数组遍历,array_solice实现增删改
实例
<?php header("Content-type: text/html; charset=utf-8"); echo '<h2>数组遍历</h2>'; echo '<hr color="red">'; $teacher = ['id'=> 100,'name'=>'song','salary'=>3000,'course'=>'PHP']; for ($i=0; $i <count($teacher) ; $i++) { echo key($teacher),'=>',current($teacher),'<br>'; next($teacher); } echo '<hr color="red">'; reset($teacher); echo '<h3>for循环实现数组遍历</h3>'; echo '<table border="1" cellspacing="0" cellpadding="3" width="300">'; echo '<caption>信息表</caption>'; echo '<tr bgcolor=green><th>ID</th><th>姓名</th><th>薪资</th><th>学科</th></tr>'; echo '<tr align=center>'; for ($i=0; $i <count($teacher) ; $i++) { echo '<td>'.current($teacher).'</td>'; next($teacher); } echo '</tr>'; echo '</table>'; echo '<hr color="red">'; echo '<h3>while循环实现数组遍历</h3>'; echo '<table border="1" cellspacing="0" cellpadding="3" width="300">'; echo '<caption>信息表</caption>'; echo '<tr bgcolor=green><th>ID</th><th>姓名</th><th>薪资</th><th>学科</th></tr>'; echo '<tr align=center>'; reset($teacher); $i=0; while ($i<count($teacher)) { echo '<td>'.current($teacher).'</td>'; next($teacher); $i++; } echo '</tr>'; echo '</table>'; echo '<hr color="red">'; reset($teacher); echo '<h3>foreach循环实现数组遍历</h3>'; echo '<table border="1" cellspacing="0" cellpadding="3" width="300">'; echo '<caption>信息表</caption>'; echo '<tr bgcolor=green><th>ID</th><th>姓名</th><th>薪资</th><th>学科</th></tr>'; echo '<tr align=center>'; foreach ($teacher as $key => $value) { echo '<td>'.$value.'</td>'; } echo '</tr>'; echo '</table>'; echo '<hr color="red">'; echo '<h3>创建个生日选择器</h3>'; echo '<p>生日选择器</p>'; $years = range(1980,2000); echo '<select name="years">'; foreach ($years as $value) { echo '<option >'.$value.'年</option>'; } echo '</select>'; echo ' '; $month=range(1, 12); echo '<select name="month">'; foreach ($month as $value) { echo '<option value="'.$value.'">'.$value.'月</option>'; } echo '</select>'; echo ' '; $day=range(1, 30); echo '<select name="day">'; foreach ($day as $value) { echo '<option value="'.$value.'">'.$value.'日</option>'; } echo '</select>'; echo ' '; echo '<button>提交</button>'; echo '<hr color="red">'; echo '<h3>array_splice实现数组增删改</h3>'; $name = ['古天乐','陈冠希','山鸡哥','张学友','张雪峰']; //保留前4个,其他都删除 print_r(array_splice($name,4)); echo '<br>'; print_r($name); echo '<hr>'; $name = ['古天乐','陈冠希','山鸡哥','张学友','张雪峰']; //删除2到-1之间的元素,包含2 print_r(array_splice($name,2,-1)); echo '<br>'; print_r($name); echo '<hr>'; $name = ['古天乐','陈冠希','山鸡哥','张学友','张雪峰']; //删除-1往右1个元素,并替换成新的元素 print_r(array_splice($name,-1,1,['木头','提莫'])); echo '<br>'; print_r($name);
运行实例 »
点击 "运行实例" 按钮查看在线实例
运行效果图:
手抄代码