Reputation: 51
I have a simple php code which retrieves data from database and displays in json format as below
[
{
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"
}
]
But I want this result in an array so that my json output should be as
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"
}
]
I am pasting the php code below:
<?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);
?>
Please help as I am new to JSON and PHP
Upvotes: 1
Views: 48
Reputation: 831
For this, you need to first json_decode the JSON from DB
$jsonArray = json_decode( $row['json'], true ); //true will give array else it will give object
Then
$output[] = json_encode( array( 'News', $jsonArray ) );
Then $output will have the the format that you need.
Upvotes: 0
Reputation: 861
$output['News']=array();
while($row=mysql_fetch_assoc($result))
{
$output['News'][]=$row;
}
Try this. It will work.
Thankyou :)
Upvotes: 0
Reputation: 510
Change
$output[]=$row;
To
$output['News'][]=$row;
This should give the output you want.
Upvotes: 5
Reputation: 7672
Change from
print(json_encode($output));
To
print(json_encode(array('News', $output)));
Upvotes: 2