我有一个资源集合来获取我所有的对话。因为前端已经编码(由另一个人),所以我想将所有这些作为对象返回,数据库的 dialog_id 作为键,对话对象作为值。
但是当我想转换从我的资源集合中获得的数组(使用 (object) $array)时,它仍然返回一个没有我设置的任何键的数组。
在我的控制器函数中,我调用:
return new DialogueResourceCollection($dialogues);
我的收藏资源如下所示:
class DialogueResourceCollection extends ResourceCollection
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$array = [];
for ($i = 0; $i < sizeof($this); $i++) {
$j = $this[$i]->dialogue_id;
$array[$j] = $this[$i];
}
return $array;
}
}
我得到什么:
[
{
"dialogue_id": 1,
"text": "example text"
},
...
我想得到什么:
{
"34" : {
"dialogue_id": 34,
"text": "example text"
},
...
}
慕村9548890