Home  >  Article  >  php array traversal skills

php array traversal skills

无忌哥哥
无忌哥哥Original
2018-06-28 10:31:211986browse

* Array traversal

* 1. foreach($arr as $key => $value) {}

* 2. Principle: Array $arr according to key value pair in sequence Take it out into $key=>$value and process it one by one, similar to callback

* 3. If you only process the value, you can omit $key: foreach($arr as $value) {}

* 4. Especially suitable for associative arrays, of course also suitable for index arrays

$teacher = ['id'=>1001, 'name'=>'peter zhu', 'salary'=> 3000, 'course'=>'php'];

//Use for loop to implement traversal of associative array

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;;

//Use while loop to implement

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;;

//Create a date picker

echo 'e388a4556c0f65e1904146cc1a846beeSelect your birthday:94b3e26ee717c64999d7867364b1b4a3';

//Generate year

$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;;

//Generation month

$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;;

//Generation day

$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;;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn