ctgScott
ctgScott

Reputation: 231

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 in 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!

Upvotes: 0

Views: 1850

Answers (2)

user609239
user609239

Reputation: 3366

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.

Upvotes: 0

christophmccann
christophmccann

Reputation: 4211

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));

Upvotes: 1

Related Questions