数组类型
数组是在程序设计中,为了方便处理,把若干变量按有序的形式组织起来的一种形式。按数组键值类型的不同,数组又可分为数值索引数组、字符关联数组。
基础知识
- 所谓的数组下标可以视为资料内容在此数组中的识别名称,通常被成为数组下标。
- 当索引值为数值时,也代表此资料内容在数组中储存位置。
- 数组中有几层索引值就被称为几维数组。
数组分类
在PHP中有两种数组:索引数组和关联数组。
- 索引(indexed)数组的索引值是整数,以0开始。当通过位置来标识东西时用索引数组。
- 关联(associative)数组以字符串作为索引值,关联数组更像操作表。索引值为列名,用于访问列的数据。
$arr = [1,2,3] // 索引数组$users = ['name'=>'laot','age'=>20]; //关联数组
一维数组
数值为单个变量(非数组)时,为一维数组。
$arr = ['name'=>'laot','url'=>'0x208.cc'];
多维数组
数组的值为数组时,这样的数组为多维数组,嵌套几层即几维数组。
$users = [['name'=>'laot'],['name'=>'李四']];
数组赋值
$arr = [];$arr[0] = 'laot';$arr['url']=>'0x208.cc';
读取元素
key——从关联数组中取得当前的键名
$arr = ['laot','0x208','人间值得'];echo key($arr); //返回0
current——返回数组中的当前单元
$arr = ['laot','0x208','人间值得'];echo current($arr); //返回 'laot'
next——将数组中的内部指针向下移动一位,并返回值。没有更多单元时返回false
$arr = ['laot','0x208','人间值得'];echo next($arr); //返回 '0x208'
prev——将数组的内部指针倒回一位,并返回值。没有更多单元时返回false
$arr = ['laot','0x208','人间值得'];var_dump(prev($arr)); //返回 FALSE
指针遍历
<?php$users = [['name'=>'laot','age'=>20],['name'=>'小明','age'=>22],['name'=>'李四','age'=>34],['name'=>'张三','age'=>19],];?><table border="1"><tr><th>编号</th><th>姓名</th><th>年龄</th></tr><?php while($user = current($users)):?><tr><td><?php echo key($users)+1;?></td><td><?php echo $user['name'];?></td><td><?php echo $user['age'];?></td></tr><?php next($users); endwhile;?></table>
遍历数组
foreach
$users = [['name'=>'laot','url'=>'0x208.cc'],['name'=>'百度','url'=>'baidu.com']];foreach ($users as $key=>$user) {echo "[{$key}] 姓名:{$user['name']} 网址:{$user['url']} <hr/>";}
list
将数组中的值赋给一组变量
$arr = ['laot','0x208'];list($name, $soft) = $arr;echo $soft;
直接显示第三个
$arr = ['laot','test','0x208.cc'];list(, , $web) = $arr;echo $web;
使用键名
$users = [['name'=>'laot','age'=>20],['name'=>'小明','age'=>22],['name'=>'李四','age'=>34],['name'=>'张三','age'=>19],];while (list('name'=>$name, 'age'=>$age) = current($users)) {echo "name: {$name} <hr/>";next($users);}
常用函数
下面是常用的数组操作函数,之后就可以自行参考官方手册 掌握其他函数了。
array_push
将一个或多个单元压入数组的末尾,这是传址操作。也就是会改变原数组。
$users =['laot','小明'];array_push($users, '张三');print_r($users);
array_pop
弹出数组最后一个单元(出栈),这是传址操作。
$users =['laot','小明'];array_pop($users);print_r($users);
array_shift
将数组开头的单元移出数组,这是传址操作。
$users =['laot','小明'];array_shift($users);print_r($users);
array_unshift
在数组开头插入一个或多个单元。
$users =['laot','小明'];array_unshift($users, '老t');print_r($users);
count
count——计算数组中的单元数目,或对象中的属性个数
$users = ['laot','小明'];echo count($users);
in_array
检查数组中是否存在某个值。
$allowImageType = ['jpeg','jpg','png'];$file = 'laot.txt';$ext = strtolower(substr(strrchr($file, '.'), 1));if (!in_array($ext, $allowImageType)) {echo 'is wrong';}
array_key_exists
检查数组里是否有指定的键名或索引。
$allowImageType = ['jpeg'=>2000000,'jpg'=>2000000,'png'=>2000000];$file = 'laot.txt';$ext = strtolower(substr(strrchr($file, '.'), 1));if (!array_key_exists($ext, $allowImageType)) {echo 'is wrong';}
array_keys
返回参数数组中的所有键名,值为数组。
$allowImageType = ['jpeg'=>2000000,'jpg'=>2000000,'png'=>2000000];$file = 'laot.jpg';$ext = strtolower(substr(strrchr($file, '.'), 1));if (!in_array($ext, array_keys($allowImageType))) {echo 'is wrong';}
array_filter
用回调函数过滤数组中的单元,下面是只获取男生的操作。
$users = [['name'=>'laot','sex'=>'男','age'=>20],['name'=>'小丽','sex'=>'女','age'=>33]];print_r(array_filter($users, function ($user) {return $user['sex']=='男';}));
array_map
为数组的每个元素应用回调函数,下面是删除用户年龄的操作。
$users = [['name'=>'laot','sex'=>'男','age'=>20],['name'=>'小丽','sex'=>'女','age'=>33]];print_r(array_map(function ($user) {unset($user['age']);return $user;}, $users));
获取所有会员名称
$users = [['name'=>'laot','sex'=>'男','age'=>20],['name'=>'小丽','sex'=>'女','age'=>33]];print_r(array_map(function ($user) {return $user['name'];}, $users));
array_values
返回数组中所有的值。
$formats = array_map(function ($user) {return implode('-', array_values($user));}, $users);print_r($formats); //输出 Array ( [0] => laot-男-20 [1] => 小丽-女-33 )
array_merge
合并一个或多个数组
$database = ['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''];print_r(array_merge($database, ['user'=>'laot','password'=>'admin888']));
array_change_key_case
将数组中的所有键名修改为全大写或小写
//键名转大写print_r(array_change_key_case($database, CASE_UPPER));//键名转小写print_r(array_change_key_case($database, CASE_LOWER));
递归改变数组键名
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];function laot_array_change_key_case(array $data, int $type=CASE_UPPER):array{foreach ($data as $k=>$v):$action = $type ==CASE_UPPER?'strtoupper':'strtolower';unset($data[$k]);$data[$action($k)] = is_array($v)?laot_array_change_key_case($v, $type):$v;endforeach;return $data;}print_r(laot_array_change_key_case($config));
递归改变数组值
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];function laot_array_change_value_case(array $data, int $type=CASE_UPPER):array{foreach ($data as $k=>$v):$action = $type ==CASE_UPPER?'strtoupper':'strtolower';$data[$k] = is_array($v)?laot_array_change_value_case($v, $type):$action($v);endforeach;return $data;}print_r(laot_array_change_value_case($config));
array_walk_recursive
对数组中的每个成员递归的应用用户函数,本函数会递归到更深层的数组中去。下面是改变数组键值的操作。
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];function change_array_value(array $data, int $type=CASE_UPPER):array{array_walk_recursive($data, function (&$value, $key, $type) {$action = $type==CASE_UPPER?'strtoupper':'strtolower';$value=$action($value);}, $type);return $data;}print_r(change_array_value($config));
var_export
输出或返回一个变量的字符串标识,第二个参数为 true 时返回字符串。
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];//生成合法的PHP代码$configContent = "<?php return ".var_export($config, true).';';file_put_contents('database.php', $configContent);
序列化
serialize
将数组序列化成字符串
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];echo serialize($config);

unserialize
将已序列化的字符串反序列化为PHP对象或数组,下面时缓存数据的操作示例。
$config = ['database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],'app'=>['name'=>'laot','url'=>'http://0x208.cc','app'=>["0x208"]]];function cache(string $name, array $data=null){$file = 'cache'.DIRECTORY_SEPARATOR.md5($name).'.php';if (is_null($data)) {$content = is_file($file)?file_get_contents($file):null;return unserialize($content)?:null;} else {return file_put_contents($file, serialize($data));}}cache('database', $config);var_dump(cache('database'));
