php数组常用方法详解

目录

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

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

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()输出结果,我们可以

$unpublished = array_filter($posts,function($post){

	return !$post->published;
});

输出的结果为

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

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

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

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

再次用var_dump输出结果

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 返回此键名的值所构成的新数组

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

$allAuth = array_column($posts,'auth');
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 在数组中随机挑选几个元素,返回这些元素的键名