Reputation: 57
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?
Upvotes: 0
Views: 265
Reputation: 2792
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
Upvotes: 1
Reputation: 24276
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
.
Upvotes: 0