gpt4 book ai didi

php - 如何在laravel中将数组中属性的JSON字符串值作为JSON数组返回

转载 作者:行者123 更新时间:2023-12-02 03:13:00 25 4
gpt4 key购买 nike

我将 JSON 字符串存储在 MySQL 表的一列中。当我尝试通过 API 以 php/json 数组的形式返回该列数据时,它仍然是一个字符串。

这是我的代码,它返回一个问题数组,在每个问题对象中,我都有一个 JSON stringify 形式的选项数组。但是,当它返回时,我不希望选项被字符串化。

    public function getQuestions($id, Request $request)
{
// return $id;

$questions = Question::where('quiz_id', $id)->orderByRaw("RAND()")->get();
$questions->makeHidden(['ans']);
// $questions->toJson(['options']);

// $questions['options'] = json_encode(questions['options']);
return $questions;
}

它像这样返回。

[
{
"id": 100000008,
"quiz_id": 10000,
"title": "কোন বানানটি সঠিক?",
"options": "[\"কলসি\",\"কলসই\",\"কলশি\",\"কলশী\"]",
"answer": 1
},
{
"id": 100000009,
"quiz_id": 10000,
"title": "কোন বানানটি সঠিক?",
"options": "[\"ঠোট\",\"ঠোঁট\",\"থট\",\"কোনটি নয়\"]",
"answer": 2
}
]

但我想要这样:

[
{
"id": 100000008,
"quiz_id": 10000,
"title": "কোন বানানটি সঠিক?",
"options": ["কলসি","কলসই","কলশি","কলশী"],
"answer": 1
},
{
"id": 100000009,
"quiz_id": 10000,
"title": "কোন বানানটি সঠিক?",
"options": ["ঠোট","ঠোঁট","থট","কোনটি নয়"],
"answer": 2
}
]

最佳答案

我刚刚添加了 $casts 将字符串转换为数组

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
protected $table = 'question';

protected $fillable = [
'quiz_id',
'title',
'opt1',
'opt2',
'opt3',
'opt4',
'ans',
'options',
'answer'
];

protected $casts = [
'options' => 'array',
];

public function quiz()
{
return $this->belongsTo('App\Quize', 'quiz_id' , 'id');
}
}

关于php - 如何在laravel中将数组中属性的JSON字符串值作为JSON数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com