0

这是我用来生成 JSON 的 PHP 文件:

<?

$databasehost = "wbw.com";
$databasename = "wtest";
$databaseusername ="w";
$databasepassword = "123";
$query = "SELECT * FROM  `and` LIMIT 0 , 30";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$sth = mysql_query($query);

if (mysql_errno()) { 
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error(); 
}
else
{
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>

它的问题是它会产生这样的结果:

[{"Reg_user_name":"nn","用户名":"ns","设备代码":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","设备名称":"office"},{"Reg_user_name":"nn","用户名":"nn","设备代码":"2366c84dead","HTTP":"https://api.ee.com/v1 /e/306ad73427e262e7","设备名称":"实验室照明"}]

但是为了使用 JSONobject 并获取其中的元素,我需要提供如下 JSON:

[ “信息”: {“Reg_user_name”:“nn”,“用户名”:“ns”,“设备代码”:“2366c84dead”,“HTTP”:“https://api.ee.com/v1//306ad73427e262r9 ","设备名称":"office"},{"Reg_user_name":"nn","用户名":"nn","设备代码":"2366c84dead","HTTP":"https://api.ee .com/v1/e/306ad73427e262e7","设备名称":"实验室照明"}]

我想知道我必须在 PHP 文件中添加什么才能使用上面的 PHP 文件自动添加带有“信息: ”标签的数据。

4

2 回答 2

2

如果你只想要一个索引,你可以改变这个

 $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows);

进入这个

 $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
 $json = array(
     'information' => $rows,
 );
    print json_encode($json);

只需将字符串索引添加到数组中,json 编码器就会自动转换它

于 2013-05-07T11:22:12.853 回答
2

检查这个

while($r = mysql_fetch_assoc($sth)) 
{
  $rows['information'][] = $r;
}
echo json_encode($rows);
于 2013-05-07T11:22:31.060 回答