我有一个简单的PHP代码,它从数据库中检索数据并以json格式显示,如下所示
[
{
S.no: "1",
News: "http://bbau.ac.in/Office%20Notice/off%20note/Aug15/1766.pdf",
Date: "2015-08-11",
news_desc: "Minute to Minute Programme on 15th August"
},
{
S.no: "2",
News: "http://bbau.ac.in/Office%20Notice/off%20note/Aug15/1760.pdf",
Date: "2015-08-11",
news_desc: "Sub - committee to look into the all sign boards of the buildings"
}
]
但是我想把这个结果放在一个数组中,这样我的json输出应该是
News:[
{
S.no: "1",
News: "http://bbau.ac.in/Office%20Notice/off%20note/Aug15/1766.pdf",
Date: "2015-08-11",
news_desc: "Minute to Minute Programme on 15th August"
},
{
S.no: "2",
News: "http://bbau.ac.in/Office%20Notice/off%20note/Aug15/1760.pdf",
Date: "2015-08-11",
news_desc: "Sub - committee to look into the all sign boards of the buildings"
}
]
我正在粘贴下面的php代码:
<?php
$con=$con=@mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect'.mysql_error());
}
mysql_select_db("mysql",$con);
$result=mysql_query("Select * from bbau_news");
$array=array();
while($row=mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
请帮助我,因为我是JSON和PHP的新手
答案 0 :(得分:5)
更改
$output[]=$row;
要
$output['News'][]=$row;
这应该提供你想要的输出。
答案 1 :(得分:2)
从
改变print(json_encode($output));
要
print(json_encode(array('News', $output)));
答案 2 :(得分:0)
$output['News']=array();
while($row=mysql_fetch_assoc($result))
{
$output['News'][]=$row;
}
试试这个。它会起作用。
谢谢你:)
答案 3 :(得分:0)
为此,您需要首先json_decode来自DB的JSON
$jsonArray = json_decode( $row['json'], true ); //true will give array else it will give object
然后
$output[] = json_encode( array( 'News', $jsonArray ) );
然后$ output将具有您需要的格式。