首页 > 解决方案 > 在 laravel 中调用未定义的方法 stdClass::count()

问题描述

我试图对我的 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]);
}

标签: phpjsonlaravelpagination

解决方案


$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)

推荐阅读