2011-10-11 175 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