我解析此JSON數組中的JSON解決新線,我要帶type
對象,並提出,在新列type2
,這是一排的我JSON行, 我獲取提供了無效的參數for foreach()由於某些行中的json中有新行。我該如何解決這個問題?通過PHP
這個人是不是歐凱
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
AndThis一個是歐凱
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
,這是我的代碼:
<?php
$con=mysqli_connect("localhost","root","","array");
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)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>
** WARNING **:當使用'mysqli'你應該使用[參數化查詢(HTTP:// PHP。 net/manual/en/mysqli.quickstart.prepared-statements.php)和['bind_param'](http://php.net/manual/en/mysqli-stmt.bind-param.php)添加用戶數據到您的查詢。 **不要**使用字符串插值或連接來完成此操作,因爲您創建了嚴重的[SQL注入漏洞](http://bobby-tables.com/)。 **絕不**將'$ _POST'或'$ _GET'數據直接放入查詢中,如果有人試圖利用您的錯誤,這會非常有害。 – tadman