猿问

如何使用 foreach 循环进行 json_decode?

我正在尝试使用 foreach 循环解析表单提交的隐藏输入文本。


<input type="hidden" id="snippet_tags" name="snippet_tags[]" value="["88","92","96","98"]">

使用以下函数获取此信息


$snippet_tags = json_decode($_POST['snippet_tags'], true);

并使用 foreach 循环解析值


foreach ($snippet_tags as $selectedOption){


                        $ins_snippet_tag_data = array(

                            'snippet_id' => $insertDataReturnLastId,

                            'tag_id' => $selectedOption,

                            'priority' => 1,


                        );


                 $this->Constant_model->insertDataReturnLastId('snippets_tags', $ins_snippet_tag_data);


                }

这里的问题是 tag_id 的值没有保存在数据库中


狐的传说
浏览 184回答 1
1回答

不负相思意

您不能使用相同的引号来分隔其中的值和字符串。您需要在值周围使用单引号。<input type="hidden" id="snippet_tags" name="snippet_tags[]" value='["88","92","96","98"]'>你写它的方式,它被视为你写value="["的,其余的被忽略。此外,由于您[]在名称之后,$_POST['snippet_tags']将是一个数组,因此您需要对其进行循环。foreach ($_POST['snippet_tags'] as $json) {&nbsp; &nbsp; $snippet_tags = json_decode($json, true);&nbsp; &nbsp; foreach ($snippet_tags as $selectedOption){&nbsp; &nbsp; &nbsp; &nbsp; $ins_snippet_tag_data = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'snippet_id' => $insertDataReturnLastId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'tag_id' => $selectedOption,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'priority' => 1,&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; $this->Constant_model->insertDataReturnLastId('snippets_tags', $ins_snippet_tag_data);&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答