2012-02-19 75 views
6

在發佈我的問題之前,我花了幾個小時查看幾個相似的答案。PHP:無法對多行的json進行編碼

我從我的數據庫中的表中檢索數據,並且我想將它編碼成JSON。但是,json_encode()的輸出僅在表格有單行時纔有效。如果有多行,則在http://jsonlint.com/處的測試會返回錯誤。

這是我的查詢:

$result = mysql_query($query); 

    $rows = array(); 

    //retrieve and print every record 
    while($r = mysql_fetch_assoc($result)){ 
     $rows['data'] = $r; 

     //echo result as json 
     echo json_encode($rows); 
    } 

這讓我下面的JSON:

{ 
"data": 
    { 
     "entry_id":"2", 
     "entry_type":"Information Relevant to the Subject", 
     "entry":"This is my second entry." 
    } 
} 


{ 
"data":{ 
     "entry_id":"1", 
     "entry_type":"My Opinion About What Happened", 
     "entry":"This is my first entry." 
    } 
} 

當我運行在http://jsonlint.com/測試,它返回此錯誤:

Parse error on line 29: 
    ..."No comment" }}{ "data": {  
    ---------------------^ 
    Expecting 'EOF', '}', ',', ']' 

不過,如果我只使用JSON的前半部分...

{ 
"data": 
    { 
     "entry_id":"2", 
     "entry_type":"Information Relevant to the Subject", 
     "entry":"This is my second entry." 
    } 
} 

...或者,如果我只測試下半年...

{ 
    "data":{ 
     "entry_id":"1", 
     "entry_type":"My Opinion About What Happened", 
     "entry":"This is my first entry." 
    } 
} 

...相同的測試將返回 「有效的JSON」。

我想要的是能夠在表中的每一行輸出一個單一的[有效的] JSON。

任何建議將非常感激。

回答

14

的問題是你吐出獨立JSON的每一行,而不是同時做這一切。

$result = mysql_query($query); 

$rows = array(); 

//retrieve and print every record 
while($r = mysql_fetch_assoc($result)){ 
    // $rows[] = $r; has the same effect, without the superfluous data attribute 
    $rows[] = array('data' => $r); 
} 

// now all the rows have been fetched, it can be encoded 
echo json_encode($rows); 

我做了小的改動是將數據庫中的每一行存儲爲$rows數組中的新值。這意味着完成後,您的$rows數組包含所有中的行,因此您可以在完成後得到正確的結果。

解決方案的問題在於,您爲數據庫的一行回顯有效的JSON,但json_encode()不知道所有其他行,因此您將獲得一系列單個JSON對象,相反到包含一個數組的單個數據。

+0

太感謝你了!所有的解決方案都可以工作,而你提供了最全面的解釋。這不僅是正確的,但我完全忽略了其他的例子做放置json_encode函數while循環之外。我很抱歉沒有注意到,並感謝您的時間。 – asraelarcangel 2012-02-19 20:22:53

3

你需要改變你的PHP代碼弄成這個樣子:

$result = mysql_query($query); 

$rows = array(); 

//retrieve every record and put it into an array that we can later turn into JSON 
while($r = mysql_fetch_assoc($result)){ 
    $rows[]['data'] = $r; 
} 
//echo result as json 
echo json_encode($rows); 
+0

+1 from me too :-) – 2012-02-19 19:04:33

+0

謝謝你,這個也可以。 – asraelarcangel 2012-02-19 20:25:52

0

我認爲你應該做

$rows = array(); 
while($r = mysql_fetch_assoc($result)){ 
    $rows[]['data'] = $r; 
} 
echo json_encode($rows); 

回聲應該放置在循環之外。

+1

是的,但每次腳本經過while循環時,這將覆蓋$ rows ['data'],所以它不會工作:) – Daan 2012-02-19 18:55:14

+1

謝謝,我沒有注意到它只是複製並粘貼他的代碼,但現在修復。 – 2012-02-19 19:01:49

+0

謝謝您的解決方案。我測試了它並且工作正常。 – asraelarcangel 2012-02-19 20:26:10

0

我是想同我的PHP,所以我來到這絲毫...

$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno"); 

    //check that records exist 
    if(mysql_num_rows($find)>0) { 
     $response= array(); 
     $response["success"] = 1; 

     while($line = mysql_fetch_assoc($find)){} 
      $response[] = $line; //This worked for me 
     } 

     echo json_encode($response); 

    } else { 
     //Return error 
     $response["success"] = 0; 
     $response["error"] = 1; 
     $response["error_msg"] = "Alumno could not be found"; 
     echo json_encode($response); 
    } 

而且,在我的Android類...

if (Integer.parseInt(json.getString("success")) == 1) { 

        Iterator<String> iter = json.keys(); 
        while (iter.hasNext()) { 
         String key = iter.next(); 
         try { 
          Object value = json.get(key); 
          if (!value.equals(1)) { 

           JSONObject jsonArray = (JSONObject) value; 

           int id = jsonArray.getInt("Id"); 
           if (!db.ExisteAlumo(id)) { 
            Log.e("DB EXISTE:","INN"); 
            Alumno a = new Alumno(); 

            int carrera=0; 
            a.setId_alumno(id); 
            a.setNombre(jsonArray.getString("nombre")); 
            a.setAp_paterno(jsonArray.getString("appaterno")); 
            a.setAp_materno(jsonArray.getString("apmaterno")); 
            a.setSemestre(Integer.valueOf(jsonArray.getString("semestre"))); 
            a.setSeccion(jsonArray.getString("seccion")); 
            if(jsonArray.getString("carrera").equals("C")) 
             carrera=1; 
            if(jsonArray.getString("carrera").equals("E")) 
             carrera=2; 
            if(jsonArray.getString("carrera").equals("M")) 
             carrera=3; 
            if(jsonArray.getString("carrera").equals("S")) 
             carrera=4; 
            a.setCarrera(carrera); 

            db.addAlumno(a); 

           } 

          } 
         } catch (JSONException e) { 
          // Something went wrong! 
         } 

       } 
0

我一定花15小時在這個問題上。上面討論的每個變化都被嘗試過最後,我能夠得到'標準解決方案'的工作。這個問題,很奇怪的是,似乎是這樣的:

當間隔設置超過14個小時,JSON似乎是無法解析它。 JSON必須有一個限制。

$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id"; 
$result=mysql_query($sql); 
if ($result){ 
    $i=0; 
    $return =[]; 
    while($row = mysql_fetch_array($result, MYSQL_NUM)){ 
     $rows[] = $row; 
    } 
    echo json_encode($rows); 
}else{ 
    echo "ERROR"; 
}