Blogger Information
Blog 34
fans 0
comment 0
visits 26579
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组字符串变量之间的转换,数组元素的回调,for循环遍历关联数组
罗盼的博客
Original
586 people have browsed it

实例

<?php
header("content-type:text/html;charset=utf-8");
/*数组与字符串转换*/
//1.list()用在索引数组上
list($name,$ask) = array('小张','没有女朋友');
echo $name.'的问题是:'.$ask.'?'.'<br>';

//2.extract($arr,$flag):关联数组转字符串,返回生成变量的数量
$arr1 = array('number'=>'1','name'=>'小张','course'=>'50');
echo extract($arr1),'<br>';//返回生成变量数目
echo '[ '."number=>".$number.'<br>',"name=>".$name.'<br>',"course=>".$course.'<br>'.']'.'<br>';

//3.变量转关联数组compact()
$id = 1;
$account ='小张';
$password =200215;
$arr2 = compact('id','account','password');
echo var_export($arr2,true);
echo '<br>';
//4.implode()数组转字符串,对值处理;
$arr3 = array('price1'=>'11','price2'=>'22','price3'=>'33','price4'=>'44');
echo implode('~',$arr3);
echo '<br>';
//explode()字符串转数组;
$string = '11-22-33-44-55-66-77-88-99-00';
print_r(explode('-',$string));
echo '<br>';

/*数组回调*/
$arr4 = array(70,66,63,56,90);
function passed($v){
  if($v<60) {
    return false;
  } 
    return true; 
}
$arr5 = array_filter($arr4,"passed");//主要用于过滤数组

var_export($arr5);
echo '<br>';

$arr6 = array('friut'=>'苹果','price1'=>50,'date'=>'2018.8.25');
function sale_friut($v,$k){
echo $k.'=>'.$v;   
}
array_walk($arr6,"sale_friut");//主要用于处理数组中键值
echo '<br>';


function number_cube($v){ 
    return $v*$v*$v;
}
$arr10=array(1,2,3,4);
 
print_r(array_map("number_cube",$arr10));//主要用于处理数组中值,可以传入多个数组,返回新数组
echo '<br>';



$arr9 = array('price1'=>'11','price2'=>'22','price3'=>'33','price4'=>'44');
$arr9_k = array_keys($arr9);
$arr9_v = array_values($arr9);
$s=count($arr9);//避免for循环重复计算数组长度
//1.用for循环遍历关联数组(方法1)
for($i=0;$i<$s;$i++){   
    //echo(array_keys($arr9)[$i].'=>'.array_values($arr9)[$i]);不识别
    echo $arr9_k[$i],'=>',$arr9_v[$i],'<br>';
}

echo '<br>';

//1.用for循环遍历关联数组(方法2)
for($i=0;$i<$s;$i++){
    echo key($arr9),'=>',current($arr9),'<br>';//输出第一个元素的键,并当前值
    next($arr9);//数组指针下移
}


?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments