合併對象我有id
type
answer
我合併id
,type
和answer
在一起,並把它們放在id2
列JSON數組,爲什麼我不能得到的輸出$答案值?解析JSON數組,並通過PHP
[{"id":"38","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
{"id":"39","answer":[{"option":"3","text":"LOW"}],"type":"b"},
{"id":"40","answer":["Hello Word"],"type":"c"}]
這是我的代碼:
<?php
$con=mysqli_connect("localhost","root","","arrayok");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$json = preg_replace("!\r?\n!", "", $json);
$jason_array = json_decode($json,true);
// id2
$id = array();
foreach ($jason_array as $data) {
if (array_key_exists('id', $data)) {
if (array_key_exists('type', $data)) {
if (array_key_exists('answer', $data)) {
foreach($data['answer'] as $ans){
$answers[] = isset($ans['text']) ? $ans['text'] : $ans;
}
$id[] = ' ID='.$data['id'].', TYPE='.$data['type'].', AWNSER='.$answers;
}
}
}
}
// lets check first your $types variable has value or not?
$ids= implode(',',$id); /// implode yes if you got values
$sql1="update user_survey_start set id2='$ids' where us_id=".$row[1];//run update sql
echo $sql1."<br>";
mysqli_query($con,$sql1);
}
}
}
mysqli_close($con);
?>
這是我的輸出:
update user_survey_start set id2=' ID=38, TYPE=a, AWNSER=Array,
和我Notice: Array to string conversion in C:\wamp64\www\json\awnser.php on line 29
我希望有$價值解答了
什麼都沒有改變。我還有'更新user_survey_start set id2 ='ID = 38,TYPE = a,AWNSER = Array,' –