Correction status:Uncorrected
Teacher's comments:
数组与字符串,变量之间的转换
<?php //索引数组转换变量 list($name,$age,$like)=['小布','18','打球']; echo $name,'今年',$age,'岁了','它喜欢',$like,'<hr>'; //关联数组转换变量 $arr1 = ['id'=>1, 'name'=>'小布','sex'=>'male','salary'=>8000]; extract($arr1); echo '我的id:',$id,',姓名:',$name,',性别:',$sex,',工资: ',$salary,'元<hr>'; //变量转换关联数组 $a='你好'; $b='世界'; $c='我来了'; $arr=compact('a','b','c'); echo var_export($arr,true),'<hr>'; echo '<pre>'; //字符串转换成数组 $arr2='吃饭,睡觉,打豆豆'; echo var_export(explode(',',$arr2,-1)),'<hr>'; //数组转换成字符串 $arr3 = ['首页','公司新闻','公司新闻','联系我们']; echo var_export(implode('|',$arr3),true),'<br>';
点击 "运行实例" 按钮查看在线实例
数组元素的回调处理
<?php //1. array_filter() $arr1 = ['id'=>1, 'name'=>'小布','sex'=>'male','salary'=>8000]; $arr2=array_filter($arr1,function ($value){ return $value!=='小布'; }); echo var_export($arr2),'<hr>'; //2. array_walk() $arr1 = ['name'=>'小布','sex'=>'male','salary'=>8000]; array_walk($arr1, function (&$value, $key, $name) { if ($value != $name) { exit('无权查看'); } else { exit($key.':'.$value); } },'小布');
点击 "运行实例" 按钮查看在线实例
用for()循环来遍历关联数组
<?php //1. foreach遍历数组 $arr1 = ['id'=>1, 'name'=>'小布','sex'=>'male','salary'=>'5000']; foreach ($arr1 as $key=>$value){ echo $key,':',$value,'<br>'; } //2. for遍历数组 $arr1 = ['id'=>1, 'name'=>'小布','sex'=>'male','salary'=>'5000']; $a=count($arr1); for ($i=0;$i<$a;$i++){ echo key($arr1),':',current($arr1),'<br>'; next($arr1);
点击 "运行实例" 按钮查看在线实例