0

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.

1 Answer 1

1

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but how can I add {"events":[ part. I think it is the name of the JSON node? Can I just write it in echo?
Still wondering when Oracle will implement an SQL JSON function within MySQL based on SELECT/INSERT and UPDATE querys (MySQL 5.5+ already makes use off JSON algorithm within EXPLAIN statement).. XML is already there within SQL function ExtractValue..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.