【发布时间】:2021-01-15 22:55:47
【问题描述】:
我正在使用 Laravel 8 来循环一些数据。我已经从我的数据库中取出了我的数据,但是我正在努力在foreach 循环中循环数据,它似乎没有给我键/值对,只有索引/值对?
$applicationOptions = ApplicationOptions::where('form_type', $form_type)->get();
foreach ($applicationOptions as $key => $value) {
// only gives me: 0 - {"id": "3", "name": "john", "age": "20"} ...
echo "${key} - ${value}";
}
但是如果我var_dump()我的$applicationOptions我可以看到数组里面的属性和原来的??
object(Illuminate\Database\Eloquent\Collection)#279 (1) {
["items":protected]=>
array(1) {
[0]=>
object(Company\MyPackage\ApplicationOptions)#289 (27) {
["table":protected]=>
string(38) "inbound_management_application_options"
["connection":protected]=>
string(5) "mysql"
["primaryKey":protected]=>
string(2) "id"
["keyType":protected]=>
string(3) "int"
["incrementing"]=>
bool(true)
["with":protected]=>
array(0) {
}
["withCount":protected]=>
array(0) {
}
["perPage":protected]=>
int(15)
["exists"]=>
bool(true)
["wasRecentlyCreated"]=>
bool(false)
["attributes":protected]=>
array(22) {
["id"]=>
int(3)
["name"]=>
string(6) "john"
["age"]=>
int(20)
}
["original":protected]=>
array(22) {
["id"]=>
int(3)
["name"]=>
string(6) "john"
["age"]=>
int(20)
}
["changes":protected]=>
array(0) {
}
["casts":protected]=>
array(0) {
}
["classCastCache":protected]=>
array(0) {
}
["dates":protected]=>
array(0) {
}
["dateFormat":protected]=>
NULL
["appends":protected]=>
array(0) {
}
["dispatchesEvents":protected]=>
array(0) {
}
["observables":protected]=>
array(0) {
}
["relations":protected]=>
array(0) {
}
["touches":protected]=>
array(0) {
}
["timestamps"]=>
bool(true)
["hidden":protected]=>
array(0) {
}
["visible":protected]=>
array(0) {
}
["fillable":protected]=>
array(0) {
}
["guarded":protected]=>
array(1) {
[0]=>
string(1) "*"
}
}
}
}
我如何访问它?看来我的查询也将整行键/值作为单个对象字符串返回...
【问题讨论】:
-
它将输出作为集合提供,我不知道你为什么需要 foreach 循环
-
所以我可以遍历列名并获取相应的值,这似乎可以做到 ->
json_decode(json_encode(ApplicationOptions::where('form_type', $form_type)->get()), true)[0]; -
您可以使用
toJson(),将集合转换为json对象。$applicationOptions = ApplicationOptions::where('form_type', $form_type)->get()->toJson(); -
你能 var_dump
$key和$value吗?