首頁  >  文章  >  php數組的遍歷技巧

php數組的遍歷技巧

无忌哥哥
无忌哥哥原創
2018-06-28 10:31:212016瀏覽

 * 陣列遍歷

 * 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;;
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn