首页 > 解决方案 > 如何仅从数组中提取值?

问题描述

我的 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"
                
            }
        ]
    }
}

标签: phparrayslaravel

解决方案


SurveyResponse::where('question_id', $this->id)->first()->answer

first()函数返回对象,然后你通过answer箭头得到字段,如果每个问题都选择了选项,否则你必须检查对象是否存在


推荐阅读