我有一个json列,我想收集id
到id2
名称的新列。
这是json专栏的一行
[{"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"}]
我的意思是如何将26,30,31 40,40,10 52,12,12
添加到新列。
我的表名是user_survey_start
我的json列名是survey_answers
而我的新ID列是id2
<?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)) {
$json = $row[0];
$jason_array = json_decode($json,true);
// id
$id = array();
foreach ($jason_array as $data){
$id[] = $data['id'];
// here code to insert/update values to db column
}
echo implode(',',$id)."</br>";
}
}
mysqli_close($con);
?>
答案 0 :(得分:2)
首先,您必须更新表架构,因此它将有一个名为id2
的新列。
ALTER TABLE `user_survey_start` ADD `id2` VARCHAR(255) NOT NULL
如果您希望此列可选,则可以从NOT
删除NOT NULL
。
然后,您只需将这些ID从JSON插入新创建的id2
列。
$id = implode(',', $id);
mysqli_query($con, "UPDATE `user_survey_start` SET `id2` = $id WHERE `id` = {$row['id']}");
答案 1 :(得分:0)
解决此代码
$id = array();
foreach ($jason_array as $data) {
$id[] = $data['id'];
}
$ids= implode(',',$id);
$sql1="update user_survey_start set id2='$ids' where id_s=".$row[1];//run update sql
echo $sql1."<br>";
mysqli_query($con,$sql1);
// awnser2
$answers = array();
foreach ($jason_array as $data) {
foreach($data['answer'] as $ans){
$answers[] =$ans['text'] ;
}
}
$answers= implode(',',$answers);
$sql3="update user_survey_start set awnser2='$answers' where id_s=".$row[1];//run update sql
echo $sql3."<br>";
mysqli_query($con,$sql3);
}
}