【发布时间】:2022-01-20 04:05:06
【问题描述】:
[
{
"user": null,
"courseId": 18
},
{
"user": {
"id": 1,
"name": "admin",
"aboutUser": null,
"files": null
},
"courseId": 1
},
]
我有一个像上面这样的数组。我想迭代上面数组上的每个项目。但是像下面这样的 foreach 循环显示错误invalid arguments supplied for foreach - Expected type 'iterable|object'. Found 'string|bool'。我该如何解决这个问题?
foreach ($response as $key) {
$count = MyCourse::where('course_id', $key['courseId'])->distinct('student_id')->count();
}
【问题讨论】:
-
你先
json_decode()回复吗? -
您声称您有一个数组,但错误表明您有一个
string|bool(尽管这在我看来不像是运行时错误) -
@NigelRen no.i 没有。我知道如果我在迭代之前做了 json_decode,我可以迭代数组。但是,在 json decding 之后的数组是一个对象数组。我在最终结果中需要一个对象数组
-
在 PHP 中,您可以将 json 解码为对象或数组。除非您添加自己的代码,否则您无法混搭。例如如果你使用
json_decode($response),你会得到一个对象(可能包含更多对象),如果你使用json_decode($response, true),你会得到一个关联数组的数组。 -
您需要额外的代码(或者可能是一个库,虽然我不知道有任何代码)来将您的
json_decode结果转换为您需要的格式。没有这样的开箱即用功能。
标签: php arrays laravel foreach laravel-8