在我看来,我正在显示一个值,但它显示为一个对象:["Jamie Rogers"]
。我想删除[" ... "]
部分。
功能:
$auditor = $audit->map(function ($user) {
return $user->name;
});
审计的初始结构:
Collection {#432 ▼
#items: array:1 [▼
0 => Score {#410 ▼
#table: "scores"
#fillable: array:3 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 [▶]
#original: array:9 [▼
"id" => 5
"score" => 0.11
"name" => "Jamie Rogers"
"created_at" => null
"updated_at" => "2017-03-19 17:47:23"
]
#relations: array:1 [▶]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
如果我使用return (string) $user->name
转换值,则不会更改它。
答案 0 :(得分:0)
要获取集合的第一个(也是唯一的)对象,请使用pluck
方法,然后使用first
方法:
$auditor = $audit->pluck('name')->first();
答案 1 :(得分:0)
map
功能在 collection
上可用,当您在集合上进行映射时,这意味着您要对数据和放大器执行某些操作;返回已处理的数据,例如您有名字&您希望以全名响应的API中的姓氏
$collection->map(function($value, $key) {//https://laravel.com/docs/5.4/collections#method-map
return [
'full_name' => $value->firstName . ' ' . $value->lastname
]
});
在 map
功能中,您传递的功能将获得两个 value
首先是值&第二个是 key
。
所以在你的情况下你也可以这样做
$collection->map(function($value, $key) {
return [
'name' => $value->name
]
})->first();
但是对于较少编码manniL's answer比我更好。
在 pluck
中,您可以获得 array_column
等关键值,但与 pluck
不同仅限收藏品。如果传递第二个参数,键也将是该列的值,您还可以告诉 pluck
方法获取值的键。另外,提及 pluck
也会返回 collection
对象。因此,您可以在该对象上使用 first
等所有方法。