2011-10-11 55 views
0

我正在嘗試將Json與我的數據庫一起使用使用php5,但遭受了一個奇怪的結果。 這個數據庫有四個字段 - 'id','Title','Thread','date',但jason的結果如下所示。PHP中的Json編碼問題

[ 
    { 
     "0": "1", 
     "id": "1", 
     "1": "Title 1", 
     "Title": "Title 1", 
     "2": "Thread 1", 
     "Thread": "Thread 1", 
     "3": "2011-10-19", 
     "date": "2011-10-19" 
    }, 
    { 
     "0": "2", 
     "id": "2", 
     "1": "Title 2", 
     "Title": "Title 2", 
     "2": "Thread 2", 
     "Thread": "Thread 2", 
     "3": "2011-10-03", 
     "date": "2011-10-03" 
    } 
] 

您可以看到結果中有重複的信息。他們從哪裏來?? 我會附上我寫的代碼... Jason & PHP大師,請賜教:'(.. 先謝謝了..我會盡力在我等待你的幫助時再解決它....

private static function queryAndFetch($tableName) 
    { 
     $query = "SELECT id, Title, Thread, date From $tableName"; 
     $result = mysqli_query(self::$link, $query); 
     if(!($result)) 
     { 
      echo "Error"; 
      exit; 
     } 


     // $posts = mysqli_fetch_assoc(self::$result); - Working 
     self::$fetchedResult = array(); 
     while($row = mysqli_fetch_array($result)) 
     { 
      self::$fetchedResult[] = $row; 
     } 
    } 

    private static function encode() 
    { 
     //print_r(self::$fetchedResult); 
     //if($format == 'json') { 
     header('Content-type: application/json'); 
     echo json_encode(self::$fetchedResult); 
     //} 
     //echo "hi".json_last_error(); 
    } 
} 

回答

2

mysqli_fetch_array返回與兩個關聯和枚舉密鑰的結果行。如果你只想要關聯數組鍵,然後用mysqli_fetch_assoc

+0

哇...我真的很愚蠢。我甚至有一個正確的代碼正確那裏,並評論出來......這一切都是從我的誤解和ASSOC陣列。謝謝你們的快速響應!!!! – Raccoon

+0

您也可以指定要'mysqli_fetch_array()'返回的內容。你也可以使用'mysqli_fetch_array(MYSQLI_ASSOC)'或'mysql_fetch_array(MYSQLI_NUM)' –

1

它看起來像你的mysqli_fetch_array($結果)返回一個關聯數組而不是索引陣列。

試試這個變化:

while($row = mysqli_fetch_array($result)) { 
    self::$fetchedResult[] = array(
     'id' => $row->id, 
     'Title' => $row->Title, 
     'Thread' => $row->Thread, 
     'date' => $row->date 
    ); 
} 

如果還是不行,請嘗試使用$行[ '身份證'],$行[ '標題'],$行[ '主題']和$行['日期「]。

或者,爲避免必須寫出每個字段,請特別更改爲mysqli_fetch_assoc($ result)。

我懷疑這是你的問題?

感謝, MyStream