MacMac
MacMac

Reputation: 35301

JSON object repeats in PHP output

This is the output:

[
    {
        "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." 
    }
]

As you may see there are repeated records added to an integer, and the row name, this is how it works:

// SQL statement and mysql_query

$posts = array();

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

How do you get it to not repeat twice, just show the row name and the record.

Upvotes: 1

Views: 316

Answers (3)

Nanne
Nanne

Reputation: 64399

You're using fetch-array: http://php.net/manual/en/function.mysql-fetch-array.php

That uses the default ('both'), but you want to specify MYSQL_ASSOCor MYSQL_NUM, and you'll get just the one :)

Upvotes: 4

John Parker
John Parker

Reputation: 54445

An easy way to do this is to use the MYSQL_ASSOC option with the mysql_fetch_array function as follows:

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

Using this option will return the "named" keys (you can use MYSQL_NUM if you simply want the numeric keys). Alternatively, you can simply use the mysql_fetch_assoc function in place of the mysql_fetch_array, as in:

while($row = mysql_fetch_assoc($result))

Upvotes: 3

Petah
Petah

Reputation: 46050

Use either

mysql_fetch_object see http://php.net/manual/en/function.mysql-fetch-object.php

or

mysql_fetch_assoc see http://php.net/manual/en/function.mysql-fetch-assoc.php

The reason you are getting that is because mysql_fetch_array returns both an associative array, and a numeric array

Upvotes: 1

Related Questions