php数组常用方法详解

众所周知,php的数组可谓是相当强大,很大一部分原因是其数组的方法非常的多而且都非常好用,下面将介绍一些非常实用的数组方法

我们先建立一个对象post以便于演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Post
{
public $title;
public $published;
public $auth;

function __construct($title,$auth,$published)
{
$this->title = $title;
$this->published = $published;
$this->auth = $auth;
}
}

$posts = [
new Post('first','jm',true),
new Post('second','vm',true),
new Post('third','cm',true),
new Post('fourth','em',false)

];
  1. array_filter 数组过滤器

可以写成闭包的形式,那样当数组被遍历的时候每一个元素就会执行该方法,将符合条件的元素return回来,然后就组成了新的数组,如果键的值为空,那么这个键将不会被保存在
新的数组里

例如我们想筛选出还没有发布的post对象,并用var_dump()输出结果,我们可以

1
2
3
4
$unpublished = array_filter($posts,function($post){

return !$post->published;
});

输出的结果为

1
2
3
4
5
6
7
8
9
10
11
array(1) {
[3]=>
object(Post)#4 (3) {
["title"]=>
string(6) "fourth"
["published"]=>
bool(false)
["auth"]=>
string(2) "em"
}
}
  1. array_map 数组元素批处理器

这个方法可就相当好用了,尤其适用于要同时改变多个对象中的属性时

假设我们要把post对象的published属性全部设置成false,可以这样做

1
2
3
4
$modified = array_map(function($post){
$post->published = false;
return $post;
},$posts); //与普通的闭包函数的位置有些许不同,闭包函数在前,要处理的数组在后

再次用var_dump输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
array(4) {
[0]=>
object(Post)#1 (3) {
["title"]=>
string(5) "first"
["published"]=>
bool(false)
["auth"]=>
string(2) "jm"
}
[1]=>
object(Post)#2 (3) {
["title"]=>
string(6) "second"
["published"]=>
bool(false)
["auth"]=>
string(2) "vm"
}
[2]=>
object(Post)#3 (3) {
["title"]=>
string(5) "third"
["published"]=>
bool(false)
["auth"]=>
string(2) "cm"
}
[3]=>
object(Post)#4 (3) {
["title"]=>
string(6) "fourth"
["published"]=>
bool(false)
["auth"]=>
string(2) "em"
}
}

神奇得发现published属性全都变成了false!

  1. array_column 返回此键名的值所构成的新数组

假设我们要返回全部的作者名

1
$allAuth = array_column($posts,'auth');
1
2
3
4
5
6
7
8
9
10
array(4) {
[0]=>
string(2) "jm"
[1]=>
string(2) "vm"
[2]=>
string(2) "cm"
[3]=>
string(2) "em"
}

以上就是三个非常实用的PHP数组的方法

附:

  • array_key_exists 判断在一个数组中是否存在这个键名

  • array_merge 合并两个数组,返回合并后的新数组

  • array_pop 将最后一个元素去除

  • array_push 在尾部追加新的元素

  • shuffle 打乱一个数组

  • array_rand 在数组中随机挑选几个元素,返回这些元素的键名

作者

马克鱼

发布于

2016-11-27

更新于

2025-10-12

许可协议