【问题标题】:How to get JSON data in this format using Laravel?如何使用 Laravel 获取这种格式的 JSON 数据?
【发布时间】:2021-07-01 11:05:24
【问题描述】:

我尝试将数据保存到 MySQL 数据库并成功保存数据。 我想以这种格式获取 JSON 数据

{
   "response_code":0,
   "results":[
      {
         "question":"Here is my question?",
         "correct_answer":"Correct Answer",
         "incorrect_answers":[
            "wrong_1",
            "wrong_2",
            "wrong_3"
         ]
      }
   ]
}

但我正在以这种格式获取我的 JSON 数据

{
   "response_code":0,
   "results":[
      {
         "question":"Here is my question?",
         "correct_answer":"right_ans",
         "incorrect_answers_1":"wrong_1",
         "incorrect_answers_2":"wrong_2",
         "incorrect_answers_3":"wrong_3",
      }
   ]
}

这是我的 MySql 数据库

请向我建议如何获得所需格式的 JSON 数据?如果您需要更多文件或信息,那么我将编辑我的问题。

 public function toArray($request)
    {
        return [
            "id"=>$this->id,
            "right_ans" =>$this->right_ans,
            "incorrect_answers_1" =>$this->wrong_1,
            "incorrect_answers_1" =>$this->wrong_2,
            "incorrect_answers_1" =>$this->wrong_3,
            "created"=>$this->created_at,
        ];
    }

【问题讨论】:

  • 请提供您如何生成当前格式的代码。
  • 这是可以实现的,但数据库设计不正确。问题和新选项表之间应该存在一对多的关系。这种设计会使您的用例变得如此简单,并且还提供了增加选项数量和问题正确答案数量的灵活性。
  • @jrcamatog 我添加了资源文件
  • @nice_dev 能否请您向我推荐一些如何实现这一目标的教程。

标签: php arrays json laravel laravel-8


【解决方案1】:

尝试像这样创建数组。它将按预期返回 json。

public function toArray($request)
{
   return [
      "id"=>$this->id,
      "right_ans" =>$this->right_ans,
      "incorrect_answers" => array (
             $this->wrong_1,
             $this->wrong_2,
             $this->wrong_3),
      "created"=>$this->created_at,
    ];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    相关资源
    最近更新 更多