JSON对象在PHP输出中重复

时间:2011-02-06 10:47:48

标签: php json

这是输出:

[
    {
        "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));

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

3 个答案:

答案 0 :(得分:4)

您正在使用fetch-array:http://php.net/manual/en/function.mysql-fetch-array.php

使用默认值('both'),但您要指定MYSQL_ASSOCMYSQL_NUM,而您只会获得一个:)

答案 1 :(得分: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))

答案 2 :(得分:1)

使用

mysql_fetch_object请参阅http://php.net/manual/en/function.mysql-fetch-object.php

mysql_fetch_assoc请参阅http://php.net/manual/en/function.mysql-fetch-assoc.php

你得到这个的原因是因为mysql_fetch_array同时返回一个关联数组和一个数值数组