简体   繁体   中英

Getting json formatted obejct from the database

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

Change

$output[]=$row;

To

$output['News'][]=$row;

This should give the output you want.

Change from

print(json_encode($output));

To

print(json_encode(array('News', $output)));
$output['News']=array();
while($row=mysql_fetch_assoc($result))
    {
        $output['News'][]=$row;
    }

Try this. It will work.

Thankyou :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM