0

I am json encoding result from a mysql query in a php file. My php script is as follows:

while ($row = mysql_fetch_array($result)) {
   $to_encode[] = $row;
}
echo json_encode($to_encode);

My Output

[
  {
    "0": "Variables",
    "topic_name": "Variables",
    "1": "pyt1.1",
    "rdf_id": "pyt1.1",
    "2": "Hello World",
    "ex_name": "Hello World",
    "3": "1",
    "line_number": "1",
    "4": "print (\"Hello World!\")",
    "code": "print (\"Hello World!\")",
    "5": "Some Comment",
    "comment": "Some Comment"
  }
]

Here, as you can see every alternate lines are redundant. I do not need lines 1,3,5...and so on.

Desired Output

[
  {
    "topic_name": "Variables",
    "rdf_id": "pyt1.1",
    "ex_name": "Hello World",
    "line_number": "1",
    "code": "print (\"Hello World!\")",
    "comment": "Some Comment"
  }
]

How to change the php script to achieve the desired output?

  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Dec 04 '15 at 15:12

2 Answers2

1

In your case you should use mysql_fetch_array() with a MYSQL_ASSOC flag:

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

Important from the docs:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.

Like referred in the docs you should use mysqli or PDO.

You can find more information here: https://stackoverflow.com/a/8891552/5297359

Community
  • 1
  • 1
swidmann
  • 2,787
  • 1
  • 18
  • 32
0

mysql_fetch_array has 2 parameters. The second parameter is the result type and is set by default to MYSQL_BOTH which means it returns both numerical and column names as keys. Use it like:

mysql_fetch_array($stmt, MYSQL_ASSOC)

NOTE: mysql_ functions are deprecated and you should consider starting to use mysqli_ functions, MySQLi class or PDO.

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50