文档首页> 常见问题> php数组的遍历技巧

php数组的遍历技巧

发布时间:2023-04-14 06:30       

* 数组遍历

* 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 '<p>选择你的生日:</p>';

//生成年

$years = range(1980, 2000);
echo '<select name="year">';
foreach ($years as $value) {
    echo '<option>'.$value.'年</option>';
}
echo '</select>';
echo '&nbsp;&nbsp;';

//生成月

$months = range(1, 12);
echo '<select name="months">';
foreach ($months as $value) {
    echo '<option value='.$value.'>'.sprintf("%02d",$value) .'月</option>';
}
echo '</select>';
echo '&nbsp;&nbsp;';

//生成日

$days = range(1, 31);
echo '<select name="days">';
foreach ($days as $value) {
    echo '<option value='.$value.'>'.sprintf("%02d",$value) .'日</option>';
}
echo '</select>';
echo '&nbsp;&nbsp;';
echo '<button>提交</button>';