首頁 > 頭條 > php數組的遍歷技巧

php數組的遍歷技巧

无忌哥哥
發布: 2018-06-28 10:31:21
原創
2039 人瀏覽過

 * 陣列遍歷

 * 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板