Correcting teacher:Guanhui
Correction status:qualified
Teacher's comments:数组是php最最最最最重要的,所以一定要吃透!
1.索引数组: 位置敏感,访问严重依赖元素在数组中的位置;键是数值的索引,表示元素的位置;默认从0开始递增
//索引数组
//定义:
$arr_day=['春节',"夏季","秋季","冬季"];//等同与 $arr_day=[0=>'春节',1=>"夏季",2=>"秋季",3=>"冬季"]
//按索引访问:
echo $arr_day[1]."===".$arr_day[3];// 输出 夏季===冬季
2.关联数组:键的类型是字符串,访问与元素在数组中的位置无关,只与它的键名相关
//关联数组
//定义:
$calss = ["id"=>1,'name'=>"王明",'sex'=>'男',"cla"=>"一班"];
//按键名访问
echo "姓名:".$calss['name']."==>".$calss['cla']; //输出 姓名:王明==>一班
1.指针遍历
//指针遍历
$users =["id"=>'1021','name'=>"陈松江",'sex'=>'男',"money"=>666.66,"pwd"=>"888888"];
// current():获取指针当前位置的数组元素的值value
// key():获取指针当前位置的数组元素的键key
echo "key=>".key($users)."-------value=>".current($users),"<br>";
//next():指针向后位移一位
next($users);
echo "next()后指定后移:key=>".key($users)."-------value=>".current($users),"<br>";
next($users);
echo "key=>".key($users)."-------value=>".current($users),"<br>";
// prev():指针前移
prev($users);
echo "prev()指针前移:key=>".key($users)."-------value=>".current($users),"<br>";
// end()直接到最后一个元素的位置
end($users);
echo "end()指针直接到最后一个元素:key=>".key($users)."-------value=>".current($users),"<br>";\
// reset():指针复位(回到第一个)
reset($users);
echo "reset()指针复位回到第一个:key=>".key($users)."-------value=>".current($users),"<br>";
2.while循环遍历
//while循环遍历
$goods =["id"=>'615','name'=>"龙虾",'unit'=>'只',"money"=>400,"num"=>"1"];
while(true){
echo "key=>".key($goods)."-------value=>".current($goods),"<br>";
if(next($goods)){
}else{
break;
}
}
3.for循环遍历
// for循环遍历
$good =["id"=>'66','name'=>"哈密瓜",'unit'=>'斤',"money"=>60,"num"=>"4"];
for($i=0;$i<count($good);$i++){
echo "key=>".key($good)."-------value=>".current($good),"<br>";
next($good);
}
4.foreach循环遍历
//foreach循环遍历 :不需要指针复位,需要手工指针指针, 自动后移
//创建一个二维数组
$shop_arr=[];
$shop_arr[]=['id'=>101,"shopname"=>"闽南一号","phone"=>15635673557];
$shop_arr[]=['id'=>111,"shopname"=>"闽南二号","phone"=>14642365236];
$shop_arr[]=['id'=>121,"shopname"=>"闽南三号","phone"=>18850471668];
foreach($shop_arr as $shop){
printf("序号=%d,店面=%s,电话=%d",$shop['id'],$shop['shopname'],$shop['phone']);
echo '<br>';
}
5.list遍历
// list()解构/解析: 索引数组
list($id, $name,$phone) = [111,"admin","18850146677"];
echo $id, $name, $phone;
echo '<br>';
// list()解构/解析: 关联数组
//创建一个二维数组
$user_arr=[];
$user_arr[]=['id'=>333,"username"=>"闽南一号","ph"=>15635673557];
$user_arr[]=['id'=>444,"username"=>"闽南二号","ph"=>14642365236];
$user_arr[]=['id'=>555,"username"=>"闽南三号","ph"=>18850471668];
foreach ($user_arr as list('id'=>$id, 'username'=>$username, 'ph'=>$ph) ) {
printf('id=%s, 姓名=%s, 电话: %s<br>', $id, $username, $ph);
}
foreach循环遍历具有其他几种循环遍历特性,推荐优先使用,特别是遍历多维数组