0

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.

3
  • Code should be indented for readability (see my edit). The mysql extension is outdated and on its way to deprecation. New code should use mysqli or PDO, both of which have important advantages, such as support for prepared statements. Commented Dec 20, 2011 at 19:50
  • possible duplicate of MySQL data to JSON via PHP, JSON encode MySQL results Commented Dec 20, 2011 at 19:51
  • Can the IDs be negative? By applying a function to the column being ordered by, MySQL won't be able to use indexes. Commented Dec 20, 2011 at 19:53

1 Answer 1

1

Have you taken a look at json_encode and json_decode?

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

Sign up to request clarification or add additional context in comments.

1 Comment

yes and i tried to use json_encode function, however i could not modify returned array into suitable format for json_encode function in php. do you know the solution?

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.