【问题标题】:PHP 7 - Warning: array_column() expects parameter 1 to be array, object givenPHP 7 - 警告:array_column() 期望参数 1 是数组,给定对象
【发布时间】:2019-12-06 07:30:30
【问题描述】:

我刚刚在我的项目中发现了一些奇怪的东西。我正在使用 PHP7.3,我正在尝试将 array_column() 函数与对象一起使用。

我正在使用命令来调用 symfony 项目中的服务 - 如果这很重要,但是我已将我的代码简化到最重要的程度。

Article.php

class Article {
    private $id;
    private $category;

    public function __construct()
    {
        $this->category = new ArrayCollection();
    }

    public function getCategory(): Collection
    {
        return $this->category;
    }

    public function addCategory(ArticleCategory $category): self
    {
        if (!$this->category->contains($category)) {
            $this->category[] = $category;
        }

        return $this;
    }

    public function removeCategory(ArticleCategory $category): self
    {
        if ($this->category->contains($category)) {
            $this->category->removeElement($category);
        }

        return $this;
    }
}

ArticleCategory.php

class ArticleCategory
{
    private $id;
    private $name;

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

我正在尝试将文章的类别作为数组获取 - 对于这种情况,我使用以下内容:

$categories = array_column($a->getCategory(), 'name'); //$a is the article object

但是,这会引发以下警告: Warning: array_column() expects parameter 1 to be array, object given


我已经尝试过的

  • 公开private $name
  • 将函数__get()__isset() 添加到private $name

但是这些都不适合我。即使 array_column 应该与 PHP >7 中的对象一起使用? 感谢您的帮助

【问题讨论】:

  • 您能否分享参考链接,为什么相信该对象受支持?根据docs:允许多维 arrayarray 对象。

标签: php symfony command php-7


【解决方案1】:

如果你需要数组使用这个$categories = $a->getCategory()->toArray();

如果您需要类别名称数组 - 使用数组映射

$categoriesName = $a->getCategory()->map(function(ArticleCategory $category) { 
    return $category->getName(); 
});

【讨论】:

  • 是的,但是如果您需要类别名称数组,请使用数组映射
  • map 函数似乎返回 ArrayCollection 而不是 array
  • 是的,它是类别名称的新ArrayCollection,但你可以调用->toArray()
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2011-09-04
  • 1970-01-01
  • 2014-06-28
相关资源
最近更新 更多