【问题标题】:Trying to get property of non-object - JSON decode试图获取非对象的属性 - JSON解码
【发布时间】:2021-09-02 05:50:59
【问题描述】:

我在使用 API 时遇到问题。

在回复中,我有一个 authors 数组字段,每个 author 有 2 个字段。

我需要管理 text 字段,但我遇到了一些错误。 这就是我操纵响应以获取作者字段的方式:

 $authorList = '';
 $authors = $publication['info']['authors']['author'];
 if (is_array($authors)) {
     foreach ($authors as $author) {
         if ($author->text === end($authors)->text) {
             $authorList .= $author->text;
         } else {
             $authorList .= $author->text . ', ';
         }
     }
     $publication['info']['authors'] = $authorList;
 } else { // just one author
     $publication['info']['authors'] = $authors;
 }

我遇到的错误是Trying to get property 'text' of non-object

【问题讨论】:

  • 显然$author 不是一个对象。试试var_dump($author) 看看它到底是什么。也许它是一个数组。
  • 从外观上看,这是一种非常复杂的方式,只不过是将一堆数组值与, 作为它们之间的分隔符...... implode 可以作为单线。
  • 是的@CBroe,我已经尝试过那种我找到更好的方法的解决方案。但在 UI 中,我看到的是对象值而不是字符串。所以目前我正在尝试这种方式。
  • 是的,你不能只在这里爆破author 数组的内容——因为这些元素本身就是对象。但是您可以使用 array_column 仅将 text 属性的值提取到一个新数组中,然后对其使用 implode。

标签: php json laravel


【解决方案1】:

感谢@CBroe 的提示,我刚刚解决了这个问题:

 $authorNames = array_column($authors, 'text');
 $authorList = implode(', ', $authorNames);
 $publication['info']['authors'] = $authorList;

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    相关资源
    最近更新 更多