Heim > Artikel > Backend-Entwicklung > PHP第七课 数组的用法2_PHP教程
学习纲要:
1.了解数组函数
2.随机输出验证码
1.数组函数:
<?php $arr=array("name"=>"user1","age"=>"30","sex"=>"man"); foreach($arr as $key=>$val){ $keys[]=$key; $vals[]=$val; } echo "<pre class="code">"; print_r($keys); echo ""; echo "
"; print_r($vals); echo ""; ?>
<?php $arr=array("name"=>"user1","age"=>"30","sex"=>"man"); $keys=array_values($arr); echo "<pre class="code">"; print_r($keys); echo ""; ?>
<?php $arr=array("user1"=>70,60,80,78,34,34,34,56,78,78); function older($var){ return ($var>60); } $arr2=array_filter($arr,"older"); echo "<pre class="code">"; print_r($arr2); echo ""; ?>
<?php $arr=array("user1"=>10,"b"=>1,"c"=>3,"d"=>30); $arr2=array_flip($arr); ksort($arr2); echo "<pre class="code">"; print_r($arr2); echo ""; ?>
<?php $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png"); sort($array1); echo "Standard sorting\n"; print_r($array1); natsort($array2); echo "\nNatural order sorting\n"; print_r($array2); ?>
<?php $arr=array("aaa","bbbbbbbbb","cc","ddddd"); //需求: //1.按照标题长度排序 //2.标题长度变成标题字符串的key //将数组中的value的长度取出,并作为一个新数组 //strlen($val)取出字符串的长度 foreach ($arr as $val) { $lens[]=strlen($val); } array_multisort($lens,SORT_ASC,$arr);//对数组进行排序,根据第一个数组来排序第二个数组 SORT_ASC表示升序排序 sort($lens); $arr2=array_combine($lens, $arr);//第一个数组作为第二个数组对应的key,返回一个新数组 echo "<pre class="code">"; print_r($arr2); echo ""; ?>
<?php $str="php,js,html,ces,div"; $arr=explode(",",$str); echo "<pre class="code">"; print_r($arr); echo ""; ?>
<?php $str="php,js,html,ces,div"; $arr=explode(",",$str); $str2=implode("-",$arr); echo "<pre class="code">"; print_r($str2); echo ""; ?>
<?php $str="php,js,html,ces,div"; $arr=explode(",",$str); $arr2=array_reverse($arr);//讲数组中的值进行倒序 $str2=implode("-",$arr2); echo "<pre class="code">"; print_r($str2); echo ""; ?>
<?php //截取总是从后往前截取 $arr = array("aa","bb","cc","dd","ee","ff","gg"); $arr2 = array_slice($arr, 0,2);//表示从0的位置截取2个 aa bb $arr3 = array_slice($arr, -3,2);//表示从后往前数到3的位置,开始截取2个//ee ff echo "<pre class="code">"; print_r($arr3); echo ""; ?>
不仅拆减,而且可以添加
<?php $arr = array("aa","bb","cc","dd","ee","ff","gg"); $arr2 = array_splice($arr, 0, 3, array("hh","ii","jj","kk"));//直接取原数组的值,并将原数组进行改变,原数组为取走以后剩下的值 echo "<pre class="code">"; print_r($arr2); echo ""; echo "
"; print_r($arr); echo ""; ?> array_merge(); "; print_r($arr); echo ""; ?>
<?php $arr = array("aa","bb","cc","dd","ee","ff","gg"); //将原数组顺序随机打乱 shuffle($arr); //取出数组的前3个 $arr2= array_slice($arr, 0 , 3); echo "<pre class="code">"; print_r($arr2); echo ""; ?>
<?php //取出1-9 a-z A-Z的数组 $a = range(1, 9); $b = range(a, z); $c = range(A, Z); //将3个数组合并 $d = array_merge($a,$b,$c); //将合并后的数组打乱 shuffle($d); //取合并后的前4位 $e = array_slice($d, 0, 4); //将$e数组变为字符串 $f = join("", $e); echo $f; ?>
转载请注明出处: http://blog.csdn.net/junzaivip