Correcting teacher:Guanhui
Correction status:qualified
Teacher's comments:while,for,foreach 都可以历遍数组,但是都有不同的使用场景,一定要合理使用。
多维数组,二维用的最多
代码如下
<?php
$staff = [];
$staff[] = '10';
$staff[] = '八戒';
$staff[] = '123@qq.com';
printf('<pre>%s</pre>',print_r($staff,true));
//关联
$staff = [];
$staff['id'] = '100';
$staff['name'] = '八戒';
$staff['email'] = '123@qq.com';
printf('<pre>%s</pre>',print_r($staff,true));
//多维
$users = [
['id'=>1,'name'=>'老公','age'=>40],
['id'=>2,'name'=>'老婆','age'=>30],
['id'=>3,'name'=>'孩子','age'=>10],
];
printf('<pre>%s</pre>',print_r($users,true));
echo $users[1]['name'];
<?php
print_r($_SERVER['QUERY_STRING']);
echo '<hr>';
parse_str($_SERVER['QUERY_STRING'], $queryArr);
print_r($queryArr);
echo '<hr>';
print_r(parse_url('http: //php.edu/0710/demo2.php?id=1&name=admin&role=1'));
echo '<hr>';
print_r(parse_url('http: //php.edu/0710/demo2.php?id=1&name=admin&role=1')['query']);
$stu = ['id' => '1982', 'name' => '梅超风', 'age' => 20, 'course' => 'php', 'grade' => 99];
// 拿键和拿值
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
// 访问完成之后,指针手工后移
next($stu);
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
// 指针前移
prev($stu);
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
// 直接访问最后一个
end($stu);
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
// 指针复位,回到第一个
reset($stu);
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
// 用while循环来实现遍历
$stu = ['id' => '1982', 'name' => '梅超风', 'age' => 20, 'course' => 'php', 'grade' => 99];
reset($stu);
while (true) {
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
if (next($stu)) continue;
else break;
}
echo '<hr>';
// 2.用for循环来实现遍历关联数组
reset($stu);
for ($i = 0; $i < count($stu); $i++) {
printf('[\'%s\']=>%s<br>', key($stu), current($stu));
next($stu);
}
echo '<hr>';
// 3.foreach循环来实现遍历关联数组,推荐使用
// 不用指针复位;不用手工移动,自动后移
$stu = ['id' => '1982', 'name' => '梅超风', 'age' => 20, 'course' => 'php', 'grade' => 99];
// 用key取键,用value取值
foreach ($stu as $key => $value) {
echo "['{$key}'] =>$value <br>";
}
代码如下
//list()解构/解析:索引数组
list($a,$b,$c) = [10,30,50];
echo $a,$b,$c;
echo '<hr>';
//list()解构/解析:关联数组
list('lesson'=>$lesson,'grade'=>$grade) = ['lesson'=>'js','grade'=>80];
echo $lesson,'===>',$grade;