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

Ada*_*tra 0 php pagination json laravel

我试图对我的 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]);
}
Run Code Online (Sandbox Code Playgroud)

And*_*alu 6

$content = json_decode($response->getContents());
$total = $content->count();
Run Code Online (Sandbox Code Playgroud)

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

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

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

$decoded = json_decode($data, true)
Run Code Online (Sandbox Code Playgroud)

这意味着它会将它解码为一个数组而不是一个对象,这使您能够

count($decoded)
Run Code Online (Sandbox Code Playgroud)