formatting JSON array output via
I am writing a small service in php to output a JSON string. The service is ultimately consumed by an Android JSONObject, if that helps. To keep it short, I have:
<?php
mysql_connect('localhost','myUser','myPwd') or die('Cannot connect to the DB');
mysql_select_db('ctgscott_myDB') or die('Cannot select the DB');
$query=mysql_query("SELECT name FROM customers ORDER BY name ASC");
while($e=mysql_fetch_assoc($query))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
The problem is the output arrives i开发者_JAVA技巧n the form:
[{"name":"Client Number1"},{"name":"Client Number2"}]
'name' is the column header for the name field in the 'customer' table and it is unnecessary for me to repeat it... I am struggling to format the output like:
{"name":["Client Number1","Client Number2"]}
Any help would be greatly appreciated. Thanks!
You need to have a multi-dimensional array instead. Try using this:
mysql_connect('localhost','myUser','myPwd') or die('Cannot connect to the DB');
mysql_select_db('ctgscott_myDB') or die('Cannot select the DB');
$query=mysql_query("SELECT name FROM customers ORDER BY name ASC");
$names['name'] = array();
while($e = mysql_fetch_assoc($query)) {
$names['name'][] = $e['name'];
}
print(json_encode($names));
here is good article to fetch data from mysql to android using php http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
精彩评论