以下方法旨在返回一个数组,其中包含另一个数组'data'
和一个Object(一些雄辩查询的结果)。
然而它返回一个包含两个对象的数组; $ data以某种方式转换为具有多个子对象的对象,而不是对象数组。应该注意的是,返回语句之前的dd($data)
表明它确实是一个对象数组。我认为处理响应的Laravel中间件会以某种方式将其作为对象返回......
任何想法如何解决这个问题?
public function getTestData($id) {
$participants = Participant::where('test_id', $id)->with('testRecords')->get();
$finalRecordValue = TestRecord::where('test_id', $id)->orderBy('created_at', 'desc')->first();
$data = [];
foreach ($participants as $participant) {
foreach ($participant->testRecords as $testRecord) {
if (!array_key_exists((int)$testRecord->capture_timestamp, $data)) {
$data[$testRecord->capture_timestamp] = (object)[
'category' => $testRecord->capture_timestamp,
'value' . "_" . $participant->id => $testRecord->score
];
} else {
$data[$testRecord->capture_timestamp]->{"value" . "_" . $participant->id} = $testRecord->score;
}
}
}
return [$data, Auth::user()->tests()->findOrFail($id)];
}
答案 0 :(得分:1)
在击败返回句子之前尝试此操作:
array_values($data);
答案 1 :(得分:0)
您可以像这样使用toArray()
:
$participants = Participant::where('test_id', $id)->with('testRecords')->get()->toArray();
https://laravel.com/docs/5.4/collections#method-toarray https://laravel.com/docs/5.7/collections#method-toarray