-1

我当前的 PHP 代码是:

<?php
//$name = $_POST['name'];

$sql = "select * from SocietyDatabase WHERE Name='Badminton'";
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result))
{
while($row=mysql_fetch_row($result))
{
$json['info'][]=$row;
}
}
echo json_encode($json); 
?>

结果是:

{"info":[["SOC003","Badminton","Sport","Me","You","me@gmail.com","badminton society"]]}

但我希望它采用这种带有“标题”的格式:

{"earthquakes": [
{
"eqid": "c0001xgp",
"magnitude": 8.8,
"lng": 142.369,
"src": "us",
"datetime": "2011-03-11 04:46:23",
"depth": 24.4,
"lat": 38.322
}
]}

那么我该如何实现呢?谢谢

4

4 回答 4

2

更改mysql_fetch_rowmysql_fetch_assoc。后者将使用列数组键填充 $row ,而前一个将仅提供数字索引。

于 2013-04-11T11:13:53.897 回答
0

改变这个

while($row=mysql_fetch_row($result))

while($row=mysql_fetch_assoc($result))
于 2013-04-11T11:14:08.350 回答
0

您可以使用PDO它,因为旧的查询方式已被弃用

http://php.net/manual/en/pdostatement.fetchall.php

$sth = $dbh->prepare("select * from SocietyDatabase WHERE Name='Badminton'");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
于 2013-04-11T11:15:10.657 回答
0

您可以按照以下示例使用 fetch_assoc 函数

$sql = "select * from clients WHERE company_name ='abc'";
$result = mysql_query($sql,$con);

$json = array();
if(mysql_num_rows($result))
{ 
    while($row=mysql_fetch_assoc($result))
    {
    $json['earthquakes']=$row;
    }
}

echo json_encode($json); 

:输出如:

{"earthquakes":{"id":"7","company_name":"abc","physical_address":"abc","postal_address":"abc","contact_name":"abc","contact_position":"abc","contact_phone":"98
于 2013-04-11T11:31:56.130 回答