首页 > 头条 > 正文

php数组的遍历技巧

无忌哥哥
发布: 2018-06-28 10:31:21
原创
2036 人浏览过

 * 数组遍历

 * 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 '

选择你的生日:

';

//生成年

$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;;
登录后复制
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板