带有字符串键的PHP JSON

时间:2013-04-11 11:10:51

标签: php json

我目前的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 个答案:

答案 0 :(得分:2)

mysql_fetch_row更改为mysql_fetch_assoc。后者将使用列数组键填充$ row,而先前将只提供数字索引。

答案 1 :(得分:0)

更改此

while($row=mysql_fetch_row($result))

while($row=mysql_fetch_assoc($result))

答案 2 :(得分: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);

答案 3 :(得分: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