繁体   English   中英

array_filter如何返回对象

[英]How array_filter is returning an object

我正在看一个教程,碰到了这个问题,可以说我有一系列具有两个属性的posts( objects ):

帖子标题和状态(是否发布)。
在我的代码中,我想返回那些尚未发布的帖子。 我知道有很多方法可以做到,但是在本教程中,显示​​的代码是这样的

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


$unpulishedPost = array_filter( $posts,function ($post){
    return !$post->published;
});

我无法理解如何在仅应返回布尔数组的情况下,return实际返回整个post对象,而不是这样的代码

$unpulishedPost = array_filter( $posts,function ($post){
     if(!$post->published) 
     return $post;
});
class Post {
    public $title;
    public $isPublished;

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

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


$unpublishedPosts = array_filter($posts, function($post) {
    return !$post->isPublished;
});

var_dump($unpublishedPosts);

此过滤器将仅返回未发布的帖子。

array(3) {
    [0] =>
    class Post#1 (2) {
      public $title =>
      string(13) "My First Post"
      public $isPublished =>
      bool(false)
    }
    [2] =>
    class Post#3 (2) {
      public $title =>
      string(13) "My Third Post"
      public $isPublished =>
      bool(false)
    }
    [3] =>
    class Post#4 (2) {
      public $title =>
      string(14) "My Fourth Post"
      public $isPublished =>
      bool(false)
    }
  }

如果返回值为true,则Array_filter返回过滤器回调的参数 否则,它将不会被推入结果数组。 这样,您可以应用自己的规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM