PHP MySQL JSON输出格式
我试图用json格式输出我的数据库信息。诀窍是teamA/teamB是数据库中的一个值 数据库如下所示:PHP MySQL JSON输出格式,php,mysql,json,Php,Mysql,Json,我试图用json格式输出我的数据库信息。诀窍是teamA/teamB是数据库中的一个值 数据库如下所示: Team timezome time fulldate teamA MST 8:30 PM 10-30-2014 teamA CST 8:30 PM 10-30-2014 我需要这样的格式 { teamA: { timezone: "MST", time: "8:30 PM", fullDate: "10-30
Team timezome time fulldate
teamA MST 8:30 PM 10-30-2014
teamA CST 8:30 PM 10-30-2014
我需要这样的格式
{
teamA: {
timezone: "MST",
time: "8:30 PM",
fullDate: "10-30-2014"
},
teamB: {
timezone: "CST",
time: "8:30 PM",
fullDate: "10-30-2014"
}
}
我可以连接到所有东西并获得基本的json输出,但我不能像我想的那样对它进行格式化
谢谢你的帮助
基思
我现在使用的格式
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['team'] = $row['team'];
$row_array['date'] = $row['date'];
$row_array['time'] = $row['time'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
它正在输出
[
{
team: "teamA",
date: "11-29-14",
time: "9:30"
},
{
team: "teamB",
date: "11-29-14",
time: "9:30"
}
]最简单的方法可能就是迭代结果集,将
团队的值作为返回数组的索引,例如$ret
,用于下面的示例。将该行分配给我们刚刚创建的索引,然后从根据$row
数组的结果构建的内部数组中取消设置团队
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$stmt = $mysqli->query('select * from my_table');
$ret = array();
while($row = $stmt->fetch_all(MYSQLI_ASSOC)):
$ret[$row['Team']] = $row;
unset($ret[$row['Team']]['Team']);
endwhile;
echo json_encode($ret);
这将产生所需的输出
$sql = "select * from tblname";
$res = mysql_query($sql);
While ($temp = mysql_fetch_assoc($res)) {
$arr [$res ['Team']] ['timezone'] = $res['timezone'];
// do it for other two fields
}
注意:不推荐使用mysql\uuz
。此代码仅用于解释和示例目的。基本JSON输出的格式是什么?您是如何生成它的?它与您想要的有什么不同?我只是在($row=mysql\u fetch\u array($result,mysql\u ASSOC)){$row\u array['team']=$row['team'];$row\u array['date']=$row['date'];$row\u array['time']=$row['time'];//推送数组中的值($json\u-response,$row\u-array)}echo json_encode($json_response)代码>感谢您的快速回复。我不得不使用fetch_assoc(),fetch all给了我一个错误。输出看起来不错,只是如果有两个相同的团队名称,它就不会循环,这两个团队名称将会存在。@user3712837添加一个groupbyteam
子句probably@user3712837添加MYSQLI_ASSOC
作为fetch_all()的参数
为了确保结果以关联数组的形式返回,当我使用fetch_all(MYSQLI_ASSOC))时,我得到了以下错误:调用未定义的方法MYSQLI_result::fetch_all()@user3712837如果您缺少驱动程序,请使用fetch_ASSOC
。)如果内存可用…fetch\u assoc
实际上比fetch\u all
的排列更少,对性能的影响也更小。谢谢您的回复。我得到了一个空值?{:{time:null}}@user3712837请不要使用mysql\
函数。在较新版本的PHP中,已弃用
和将被删除
。请考虑使用<代码> MySqLII< <代码>或<代码> PDO < /代码>。