【发布时间】:2017-02-25 11:47:45
【问题描述】:
我有一个带有 id type answer 的 json 数组,我正在合并 id、type 和 answer 并将它们放在 id2 列中,那为什么我不能在输出中获取 $answers 值?
[{"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
我想拥有 $answers 的价值
【问题讨论】:
-
没有改变。我还有
update user_survey_start set id2=' ID=38, TYPE=a, AWNSER=Array,