数组到字符串的转换Laravel 5.6

时间:2018-08-16 04:53:45

标签: php laravel

    $data = $request->all();

    if (!empty($data))
    {
        foreach ($data as $key => $value)
        {
            if($key === "_token")
            {
                continue;
            }

            $val = [
                'questionnaire_id' => $questionnaire_id,
                'question_id' => $key,
                'answer' => $value
            ];

            $answer = Answer::create($val);
        }
    }

这是我的数组

    {
"_token": "URP1tlRfoD0RFMYIgVIyBX1AYaobDsQU2wnvxC1r",
"questionnaires_id": "5",
"questions": {
"2": "a",
"10": "3",
"11": "b",
"44": "2018-08-01"
}
}

这是我的模型课

class Answer extends Model
    {
        protected $fillable = [
            'questionnaire_id', 'question_id', 'answer'
        ];
    }

4 个答案:

答案 0 :(得分:0)

如果仅要将数组转换为字符串,则应使用json_encode()之类的php函数

答案 1 :(得分:0)

要在数据库/模型中存储阵列,可以执行以下操作:

protected $casts = [
    'answer' => 'array'
];

$answer可以是:

$answer = array($your_data);

答案 2 :(得分:0)

像这样更改代码

    $qs = $request->questions;
    $qr = $request->questionnaires_id;
    foreach ($qs as $k => $q)
    {
        $val = [
            'questionnaire_id' => $qr,
            'question_id' => $k,
            'answer' => $q
        ];
        $answer = Answer::create($val);
    }

答案 3 :(得分:0)

您应遵循此流程。

$data = $request->all();

    if (!empty($data))
    {
        $questionnaires_id = 0;
        $questions = [];
        foreach ($data as $key => $value)
        {
            if($key === "_token")
            {
                continue;
            }

            if($key === "questionnaires_id")
            {
                $questionnaires_id = $value;
            }

            if($key === "questions")
            {
                $questions = $value;
            }
        }

         foreach ($questions as $key => $value) {
            $val = [
                'questionnaire_id' => $questionnaires_id,
                'question_id' => $key,
                'answer' => $value
            ];

            $answer = Answer::create($val);
         }
    }