Correcting teacher:Guanhui
Correction status:qualified
Teacher's comments:内容有点少!list一定好好利用,可以帮助写出优雅的代码。
<?php
// 创建数组
$staff = [];
// 1.索引数组,以追加的方式添加
$staff[] = '20';
$staff[] = 'abc';
$staff[] = '123@qq.com';
printf('<pre>%s</pre>', print_r($staff, true));
// 2.关联数组
$staff = [];
$staff['id'] = '20';
$staff['name'] = 'abc';
$staff['email'] = '123@qq.com';
printf('<pre>%s</pre>', print_r($staff, true));
// 3.多维数组,二维用的最多
$users = [
['id' => 1, 'name' => '小明', 'age' => 20],
['id' => 2, 'name' => '小李', 'age' => 21],
['id' => 3, 'name' => '小刘', 'age' => 22],
];
printf('<pre>%s</pre>', print_r($users, true));
// 4.如何拿到小刘?
echo $users[2]['name'];
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/demo1.php?id=1&name=admin&role=1'));
echo '<hr>';
print_r(parse_url('http: //php.edu/0710/demo1.php?id=1&name=admin&role=1')['query']);
$stu = ['id' => '01', '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));
// 1.用while循环来实现遍历
$stu = ['id' => '01', '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' => '01', 'name' => '小芳', 'age' => 20, 'course' => 'php', 'grade' => 99];
// 用key取键,用value取值
foreach ($stu as $key => $value) {
echo "['{$key}'] =>$value <br>";
}
$stu = ['id' => '01', 'name' => '小芳', 'age' => 20, 'course' => ['php', 'js', 'css'], 'grade' => 99];
foreach ($stu as $value) {
echo is_array($value) ? print_r($value, true) : $value;
}
// 1.list():针对索引数组,解析/解构
list($a, $b, $c) = [10, 20, 30];
echo $a, $b, $c;
echo '<hr>';
// 2.list():关联数组,解析/解构
list('lesson' => $lesson, 'grad' => $grad) = ['lesson' => 'html', 'grad' => 90];
echo $lesson, '===>', $grad;
echo '<hr>';
list('id' => $id, 'name' => $name, 'age' => $age) = ['id' => '01', 'name' => '小李', 'age' => 21];
foreach ($users as list('id' => $id, 'name' => $name, 'age' => $age)) {
printf('id=%s, 姓名=%s, 年龄:%s<hr>', $id, $name, $age);
}