Rumah  >  Artikel  >  php数组的遍历技巧

php数组的遍历技巧

无忌哥哥
无忌哥哥asal
2018-06-28 10:31:212024semak imbas

 * 数组遍历

 * 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),&#39;=>&#39;,current($teacher),&#39;<br>&#39;;
next($teacher);
}
echo &#39;<hr color="red">&#39;;

//用while循环来实现

reset($teacher);
$i = 0;
while ($i<count($teacher)) {
echo key($teacher),&#39;=>&#39;,current($teacher),&#39;<br>&#39;;
next($teacher);
$i++;
}
echo &#39;<hr color="red">&#39;;
//foreach($arr as $key=>$value):数组专用的遍历语法结构
echo &#39;<h4>讲师信息</h4>&#39;;
echo &#39;<ul>&#39;;
foreach ($teacher as $key => $value) {
    echo &#39;<li>&#39;.$key.&#39;:&#39;.$value.&#39;</li>&#39;;
}
echo &#39;</ul>&#39;;
echo &#39;<hr color="red">&#39;;
//如果只对值感兴趣
echo &#39;<table border="1" cellpadding="3" cellspacing="0" width="300">&#39;;
echo &#39;<caption>讲师信息表</caption>&#39;;
echo &#39;<tr bgcolor="lightskyblue"><th>ID</th><th>姓名</th><th>工资</th><th>课程</th></tr>&#39;;
echo &#39;<tr>&#39;;
foreach ($teacher as $value) {
    echo &#39;<td align="center">&#39;.$value.&#39;</td>&#39;;
}
echo &#39;</tr>&#39;;
echo &#39;</table>&#39;;
echo &#39;<hr color="red">&#39;;

//创建一个日期选择器

echo 'e388a4556c0f65e1904146cc1a846bee选择你的生日:94b3e26ee717c64999d7867364b1b4a3';

//生成年

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

//生成月

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

//生成日

$days = range(1, 31);
echo &#39;<select name="days">&#39;;
foreach ($days as $value) {
    echo &#39;<option value=&#39;.$value.&#39;>&#39;.sprintf("%02d",$value) .&#39;日</option>&#39;;
}
echo &#39;</select>&#39;;
echo &#39;  &#39;;
echo &#39;<button>提交</button>&#39;;
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php常用数组函数(三)Artikel seterusnya:php常用数组函数(四)