【问题标题】:Call to undefined method stdClass::count() in laravel在 laravel 中调用未定义的方法 stdClass::count()
【发布时间】:2020-06-02 04:53:19
【问题描述】:

我试图对我的 JSON 响应进行分页,但出现这样的错误

调用未定义的方法 stdClass::count()

我使用 guzzle 来自 Laravel API 的 JSON 响应......

这是我的控制器代码

public function index()
{
    $response =  $this->client->get('getUserIndex')->getBody();
    $content = json_decode($response->getContents());
    $total = $content->count();
    $paginationRecord = CollectionPaginate::paginate($content, $total, '15');
    return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord->data]);
}

【问题讨论】:

  • 请发帖dd($content)
  • $content 是一个对象,而不是一个集合,你不能在上面使用->count()。你必须使用count($content)

标签: php json laravel pagination


【解决方案1】:

$content 是一个对象,不是一个集合或数组,你可以使用 php 方法 count 和 array get $total

请改成

 public function index()
        {


            $response =  $this->client->get('getUserIndex')->getBody();
            $content = json_decode($response->getContents(),true );
            $total = count($content);
            $paginationRecord = CollectionPaginate::paginate($content, $total, '15');
            return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord->data]);

}

【讨论】:

  • 嗨,先生.. 刚刚收到错误消息,例如“传递给 App\Helpers\CollectionPaginate::paginate() 的参数 1 必须是 Illuminate\Support\Collection 的实例,给定的 stdClass 实例”
  • 我认为您需要先了解响应数据。可能是数组被另一个键嵌套。
【解决方案2】:
$content = json_decode($response->getContents());
$total = $content->count();

我不完全确定你为什么认为 json_decode 的结果会有一个 count 方法? JSON 解码总是产生一个通用对象 (stdClass),因为 PHP 解释器无法知道它代表一个可用的类。

->count 方法可用于 Countable 实现(例如 ArrayCollection)。如果您期望一个 Countable 类,那么您可以有一个工厂来从 JSON 构建您的对象,或者尝试将 stdClass 转换为 ArrayCollection。

否则,如果你的JSON数据是一个有效的数组,你可以尝试使用

$decoded = json_decode($data, true)

意味着它将它解码为一个数组而不是一个对象,这使您可以这样做

count($decoded)

【讨论】:

  • 嗨,先生.. 刚刚收到错误消息,例如“传递给 App\Helpers\CollectionPaginate::paginate() 的参数 1 必须是 Illuminate\Support\Collection 的实例,给定的 stdClass 实例”
  • @adaminho 请注意,$content 将通过 json_decode 成为数组或 stdClass 对象,但绝不会成为 Illuminate\Support\Collection 的实例。试试$collection = new \Illuminate\Support\Collection($decoded); $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');
  • @jrswgtr 非常感谢先生,我可以将数据传递给查看
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 2019-11-20
相关资源
最近更新 更多