php - 如何仅从数组中提取值?
问题描述
我的 laravel json 资源在这里
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\SurveyResponse;
class SurveyQuestionsCollection extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
if(isset($this->id)) {
return [
'id' => $this->id,
'survey_id' => $this->survey_id,
'question' => $this->question,
'sequence' => $this->sequence,
'type' => $this->type,
'options' => $this->options,
'selected_option'=>SurveyResponse::where('question_id',$this->id)->first()->pluck('answer'),
];
} else {
return [];
}
}
}
回应是这样的
{
"statusCode": 200,
"message": "Survey fetch successfully...",
"data": {
"user_survey_id": 1,
"questions": [
{
"id": 1,
"survey_id": 1,
"question": "what is current version of Bootsarap ?",
"sequence": "1",
"type": "Singleselect",
"options": "3,4,5,6",
"selected_option": [
"Options 1"
]
}
]
}
}
我需要这个回应
{
"statusCode": 200,
"message": "Survey fetch successfully...",
"data": {
"user_survey_id": 1,
"questions": [
{
"id": 1,
"survey_id": 1,
"question": "what is current version of Bootsarap ?",
"sequence": "1",
"type": "Singleselect",
"options": "3,4,5,6",
"selected_option": "Options 1"
}
]
}
}
解决方案
SurveyResponse::where('question_id', $this->id)->first()->answer
first()
函数返回对象,然后你通过answer
箭头得到字段,如果每个问题都选择了选项,否则你必须检查对象是否存在
推荐阅读
- python - Fitler DateTimeField 与 django-filter 中的 DateFilter
- apache-spark - PySpark:仅针对某些字段读取具有已定义固定类型的 JSON 文件
- javascript - google drive api TypeError:无法读取未定义的属性“驱动器”或类型错误:无法读取未定义的属性“文件”
- keras - Keras 教程 - 获取规范化层时出错
- python - 如何使用 ffplay 打开 rtsp 流并将帧提供给 opencv?
- google-sheets - 谷歌表格上面的公式突出显示不匹配
- python-3.x - 使用 librosa 将语音 A 转换为语音 B
- excel - VBA Userform - 由于句点/逗号而过滤的问题
- javascript - 在每次出现字符时拆分字符串,但将字符保留在新数组中
- c# - 我想用另一个列表搜索字符串项目列表。可能吗?