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 在數組中隨機挑選幾個元素,返回這些元素的鍵名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章