数组与字符串,变量之间的转换
实例
<?php header("content-type:text/html;charset=utf-8"); $user = ['id'=>'1','name'=>'aa','gender'=>'male','age'=>'29','tel'=>123]; print_r($user);//打印数组 echo '<hr>'; echo var_export($user,true);//按字符串打印数组 echo '<hr>'; print_r(array_values($user));//打印数组的值 echo '<br>'; print_r(array_keys($user)); echo '<hr>'; //用于反转/交换数组中所有的键名以及它们关联的键值。返回一个数组 print_r(array_flip($user)); echo '<hr>'; //用于在一次操作中给一组变量赋值(索引数组) list($name, $age, $team) = ['科比','40','湖人']; echo "祝{$team}名宿{$name}{$age}岁生日快乐"; echo '<hr>'; //关联数组转变量 extract($user); echo 'id:',$id,'姓名:',$name,'性别:',$gender,'年龄:',$age,'电话:',$tel; echo '<hr>'; $name = '乔丹'; $position = '后卫'; $height = 198; $arr = compact('name','position','height');//参数用变量名的字符串形式 print_r($arr); echo '<hr>'; $player = 'kobe,guard,lakers'; var_export(explode(',',$player));//将字符串拼接成数组 echo '<hr>'; $nba = ['spurs','bulls','celtics','worries','jazz']; echo '<a href="">'. implode('</a>|<a href="">',$nba);//将数组分割成字符串
运行实例 »
点击 "运行实例" 按钮查看在线实例
数组元素的毁掉处理
实例
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/8/25 * Time: 23:30 */ $arr1 = ['math','english','history','physical','0','',null,false]; print_r(array_filter($arr1)); echo '<hr>'; //利用回调函数去掉数组中的值 print_r(array_filter($arr1,function ($v){ return $v !=='math'; })); echo '<hr>'; $arr2 = ['name'=>'Jordan']; array_walk($arr2,function($v,$k){ echo "my {$k} is {$v} "; });
运行实例 »
点击 "运行实例" 按钮查看在线实例
用for()循环来遍历关联数组
实例
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/8/26 * Time: 0:05 */ $arr = ['name'=>'kobe','age'=>40,'position'=>'guard']; $keys = array_keys($arr); for($i=0;$i<count(array_keys($arr));$i++){ $j = $keys[$i]; echo $keys[$i],'=>',$arr[$j],'<br>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例