Php 通过格式化JSON数组输出

Php 通过格式化JSON数组输出,php,android,mysql,json,Php,Android,Mysql,Json,我正在用php编写一个小服务来输出JSON字符串。如果有帮助的话,该服务最终会被Android JSONObject使用。简而言之,我有: <?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

我正在用php编写一个小服务来输出JSON字符串。如果有帮助的话,该服务最终会被Android JSONObject使用。简而言之,我有:

<?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();
“name”是“customer”表中name字段的列标题,我无需重复它。。。我正在努力格式化输出,如:

{"name":["Client Number1","Client Number2"]}

任何帮助都将不胜感激。谢谢

您需要一个多维数组。尝试使用以下方法:

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

下面是一篇使用php从mysql获取数据到android的好文章。希望你喜欢。

谢谢,克里斯托弗!看来我们已经走到一半了。现在的输出是:{“name”:[{“name”:“Client Number2”},{“name”:“Test Client”}]}对不起,让我来清理一下:{“name”:[{“name”:“Client Number1”},{“name”:“Client Number2”}]}关于从[]中提取“name”还有什么想法吗?我遇到的问题是,在消费端,如果不进行额外的解析,Android JSONObject将采用键/值或键/数组()对。当然,更多的工作可以放在那里。。。只是试着让它在一边或另一边保持简单。:)将“mysql\u fetch\u assoc($query)”更改为“mysql\u fetch\u row($query)给了我:。。。{“名称”:[[“客户编号1”],[“客户编号2”]}。。。如此接近。也许我会在接收端继续解析。对不起,那是我的错。我已经修改了上面的代码,应该可以更正它了。太棒了!它工作得很好。输出={“名称”:[“客户编号1”,“客户编号2”]}…谢谢Christopher!该死,我是StackOverflow的新手,他们不让我回答这个问题。。。喝倒采
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));