PHP 新手入門指南 - 數組過濾

讓我們來點插曲,了解下如何進行一些數據操作,這里會講到如何通過數組函數對數據進行過濾數據提取。

小實踐

建立一個 index.php 文件。在這其中,我們先定義個類 Post 和相應數據

<?php

class Post 
{
    public $title;

    public $published;

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

$posts = [
    new Post('My First Post', true),
    new Post('My Second Post', true),
    new Post('My Third Post', true),
    new Post('My Fourth Post', false)
];

接下來我們要對 $posts 數組進行一些操作。

array_filter

array_filter — 用回調函數過濾數組中的單元。更多內容

在文件 index.php 中追加內容:

// 過濾數據得到未發布的文章
$unpublishedPosts = array_filter($posts, function($post) {
    return ! $post->published;
});
var_dump($unpublishedPosts);

// 過濾得到已發布的文章
$publishedPosts = array_filter($posts, function($post) {
    return $post->published;
});
var_dump($publishedPosts);

array_map

array_map — 為數組的每個元素應用回調函數。更多內容

// 調整數據格式
$modified = array_map(function($post) {
    return ['title' => $post->title];
}, $posts);

array_column

array_column — 返回數組中指定的一列。更多內容

// 提取列(這里前提是 title 作為 Post 的屬性其訪問修飾符必須是 public)
$titles = array_column($posts, 'title');

var_dump($titles);

最后

這里簡單介紹了如何通過數組函數過濾大操作相關的數據,如果想要了解更多關于數組函數的信息,請參考 PHP手冊:數組函數

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容