如何将json对象拆分为3部分id
awnser
和type
?
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"b"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"c"}]
和数据库名称:
array
表名称:user_survey_start
JSON列名称:survey_answers
,这是我的代码: <?php
$con=mysqli_connect("localhost","root","","arrayy");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers` FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
}
mysqli_close($con);
?>
最佳答案
尝试使用json_decode()
<?php
$sql="SELECT `survey_answers` FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql))
{
while ($row = mysqli_fetch_row($result))
{
$json = $row[0];
$jason_array = json_decode($json,true);
foreach ($jason_array as $data){
$id[] = $data['id'];
$answer[] = $data['answer'];
$type[] = $data['type'];
// here code to insert/update values to db column
}
echo implode(',',$id);
echo implode(',',$answer);
echo implode(',',$type);
}
}