Blogger Information
Blog 33
fans 0
comment 0
visits 24455
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组遍历,数组与字符串变量转换及数组元素回调 20180824 23:00
EmonXu的博客
Original
593 people have browsed it
  1. 编程 : 数组与字符串,变量之间的转换
    2.编程: 数组元素的回调处理
    3.编程: 用for()循环来遍历关联数组

代码如下:

实例

<?php

//1.编程 : 数组与字符串,变量之间的转换
//2.编程: 数组元素的回调处理
//3.编程: 用for()循环来遍历关联数组

//编程: 用for()循环来遍历关联数组
$arr1 = ['name'=>'詹姆斯','team'=>'湖人','rank'=>1];
for ($i=0;$i<count($arr1);$i++){
    echo key($arr1),':',current($arr1),'<br>';
    next($arr1);
}
echo '<hr>';
foreach($arr1 as $k => $v){
    echo $k,':',$v,'<br>';
};
echo '<hr>';
//数组与变量与字符串之间的转换
//1.list() 把数组中的元素转为变量: 用在索引数组上


//list($name, $team, $rank) = ['詹姆斯','湖人',1];
$arr1 = ['name'=>'詹姆斯','team'=>'湖人','rank'=>1];
list($name, $team, $rank) = array_values($arr1);
echo $team,'的',$name,'是NBA排名第',$rank,'的球星','<br>';

//2. extract($arr, $flag): 关联数组转为变量
extract($arr1);
echo $team,'的',$name,'是NBA排名第',$rank,'的球星','<br>';
//extract():返回变量的数量
echo extract($arr1),'<hr>';

//3.compact(): 将变量转为关联数组
$name = '杜兰特';
$team = '勇士';
$rank = 2;
$arr2 = compact('name','team','rank');

echo var_export($arr2,true);
echo '<hr>';

//4.explode():将字符串转换数组
$lang = '戴维斯,鹈鹕,3';
$arr3 = explode(',',$lang);
echo var_export($arr3),'<br>';
echo var_export(explode(',',$lang,2)),'<br>';
echo var_export(explode(',',$lang,-2)),'<br>';//最常用

//5.implode($glue, $arr)
$arr4 = ['库里','勇士',3];
echo var_export(implode($arr4),true),'<br>';
echo var_export(implode('->',$arr4),true),'<hr>';

//编程: 数组元素的回调处理
//1. array_filter():回调处理数组中的每个元素的值,仅返回结果为true的元素
$arr5=[0,'',false,null,'test'];

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

$arr6=[0,1,2,3,4,5,6];
echo var_export(array_filter($arr6,function ($a){
    return $a>3;
}));

echo '<br>';

//2. array_walk():对数组中每个元素的键和值进行处理

echo var_export(array_walk($arr1,function ($value,$key,$name){
    if ($value==$name){
        exit('头号球星') ;
    }    else{
        exit('非头号球星') ;
    }
},'詹姆斯'),true);

运行实例 »

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


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
Author's latest blog post