简体   繁体   中英

Creating JSON array with information retrieved from database

I am trying to create a JSON array with the information selected from a database but I cannot give the array a name.

while($row = mysql_fetch_array($result))
{
        $arr = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
        echo json_encode($arr);
}

I want to see the result;

{"events":[{"isim":"eere","yer":"dddd","top":"asdfsdffgdfgdfg","tar":"2013-10-18","saat":"12:46"}{"isim":"fhjfr","yer":"yhjrhj","top":"ryjryjrj","tar":"2013-10-30","saat":"12:45"}{"isim":"sfsgsg","yer":"sfgssfg","top":"sgsfgsg","tar":"2013-10-31","saat":"12:45"}]}

But I cannot see the

{"events":[

in the beggining and

]}

at the end.

Thank you.

To generate valid JSON, you first need to add everything to a multi-dimensional array and only then when that is complete, encode it:

$arr = array();
while($row = mysql_fetch_array($result))
{
        $arr[] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
        // or perhaps just: $arr[] = $row;
}
echo json_encode($arr);

Also note that the mysql_* functions are deprecated.

To put everything under an events key, you would need something like:

$arr['events'][] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);

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