2017-02-23 78 views
0

我解析此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); 
?> 
+1

** 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

回答

1

更換新的符合\ n JSON解碼之前:

$json = preg_replace('/\r|\n/','\n',trim($json)); 

$jason_array = json_decode($json,true); 
+0

解決,你是Awsomeeeeeeeee,Appriciate它 –

1

問題是無效的JSON格式。

如果您的文字內容有多行,則應該使用\n,而不是輸入回車。

[{"id":"26","answer":[{"option":"4","text":"Hello\n"}],"type":"3"}] 
               ^^ 
+0

這個json是問題的描述性問題和用戶輸入的。我有太多的行,我該怎麼辦? –

+0

@SedricHeidarizarei首先,緩解大寫字母。如果您需要批量修復數據,是否可以手動編輯這些數據或者有太多的方法?有錯誤的模式嗎? – tadman

+1

@SedricHeidarizarei在存儲記錄或執行'json_decode()'之前,將所有EOF字符替換爲'\ n'。 –