2011-02-06 109 views
1

这是输出:JSON对象在PHP输出重复

[ 
    { 
     "0": "1", 
     "cat_id": "1", 
     "1": "Hello World!", 
     "post_title": "Hello World!", 
     "2": "1296943703", 
     "post_date": "1296943703", 
     "3": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", 
     "post_content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." 
    } 
] 

正如你可以看到有反复加上一个整数的记录,与该行的名称,这是它如何工作的:

// SQL statement and mysql_query 

$posts = array(); 

while($row = mysql_fetch_array($result)) 
{ 
    $posts[] = $row; 
} 
mysql_free_result($result); 
die(json_encode($posts)); 

如何让它不重复两次,只显示行名和记录。

回答

4

您使用获取阵列:http://php.net/manual/en/function.mysql-fetch-array.php

使用默认的(“两”),但要指定MYSQL_ASSOCMYSQL_NUM,你会得到的只是一个:)

+0

哇,一点点修复,使用`mysql_fetch_assoc`,谢谢! :D – MacMac 2011-02-06 10:53:41

+0

我真的很感兴趣,为什么这会得到-1? – Nanne 2011-02-06 11:03:22

+0

@Nanne也很想知道为什么我的回答也被低估了。有趣的是,只有其中一个没有。 – 2011-02-06 11:07:33

3

一个简单的方法做,这是如下使用MYSQL_ASSOC选项与mysql_fetch_array功能:

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 

使用此选项将返回“命名”键(可以使用MYSQL_NUM如果你只是想数字键)。或者,你可以简单地使用mysql_fetch_assoc功能到位mysql_fetch_array的,如:

while($row = mysql_fetch_assoc($result))