php - 在 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]);
}
解决方案
$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)
推荐阅读
- ios - 如何使用 swift 扩展获取本地货币的 IAP 价格
- image - 从背景图像进行粒子分割
- python - main.py => 其他计算机 => 其他人可以使用 main.py 但没有安装 python,如何?
- python - 我在 python 中的字符计数器有问题
- mysql - 当我从 SQLworkbench 切换到 PHPmyAdmin 时,Mysql 查询突然不再工作
- c# - C# WPF 泛型错误:...违反类型参数 'Parent' 的约束
- python - 语法问题,如何将字符串添加到函数的参数中?
- pytorch - 了解用于序列分类的 LSTM 架构
- python - 根据另一个数据框的值从一个数据框中删除行
- android - 错误:-主体可能正常完成,导致返回“null”,但返回类型可能是不可为空的类型