aliaktas
aliaktas

Reputation: 165

convert mysql query into json object via php

i have a problem to modify and convert php array to json object, the array forms via mysql query. desired json format is as follows:

{
"uy":[
        {
    "pid": "23334",
    "t":[
        {
        "k": "Serkan AKYAKA",
        "msj":"message1",
        "tar": "24 Mayis 2011"
        },
        {
        "k": "Ali AKTAS",
        "msj":"message1",
        "tar": "01 Nisan 2011"
        }           
        ]
         },
    {
    "pid": "234534",
    "t":[
        {
        "k": "Gulden DURAY",
        "msj":"message1",
        "tar": "17 Haziran 2011"
        },
        {
        "k": "Ali AKTAS",
        "msj":"message1",
        "tar": "05 Mayis 2011"
        }           
        ]
    }  
] 
} 

i have a table including data as follows:

pid(not unique), k(not unique), msg(message text), date(date of the message)

i have php code like below however i could not manage to convert json object as i want

$op='{';
mysql_select_db($database, $rdb);
$query_tav="SELECT pid, k, msj, tar FROM u_t WHERE rid=1 ORDER BY ABS(id)";
$r_tav = mysql_query($query_tav, $rdb) or die(mysql_error());
$tav = mysql_fetch_assoc($r_tav);
row_sayi = mysql_num_rows($r_tav);
if ($row_sayi > 0) {
    do {
        $op=$op.'"t":['.json_encode($tav).'],';
    } while ($tav = mysql_fetch_assoc($r_tav));
}
$op=$op.'}';

the php code above has many missing points however i can not figure out how to do it.

thanks for your help.

Upvotes: 0

Views: 1709

Answers (1)

student
student

Reputation: 213

Have you taken a look at json_encode and json_decode?

http://php.net/manual/en/function.json-encode.php

Upvotes: 1

Related Questions