mayur bhagat
mayur bhagat

Reputation: 209

create custom json array from database result in php?

Hi I have some table say fro example table1 ,table2 in my mysql databse. I need to get following json result from php. Can anyone suggest how to achieve this? any good tutorial doing same is also helpful. I am able to convert database result in simple json response but custom response is something difficult for me.

{
response:ok
tables:[
{
    name:table name
        data:[
                {
                fieldname1:value1
                fieldname2:values2
                },
                {
                fieldname1:value1
                fieldname2:value2
                }
                .
                .
            ]               
},
{
    name:table name1
        data:[
                {
                fieldname1:value1
                fieldname2:values2
                },
                {
                fieldname1:value1
                fieldname2:value2
                }
                .
                .
            ]               
},

]
}
}

Upvotes: 0

Views: 3983

Answers (1)

Leonardo Rossi
Leonardo Rossi

Reputation: 3032

Quoting from How to convert mysql data base table data in json using php, once you have your table names you can do for each of them.

$result = array();
$result['response'] = 'ok'
foreach ($tables as $tableName) {       
    $query = mysql_query("SELECT * FROM $tableName");
    $rows = array();
    while($row = mysql_fetch_assoc($query)) {
        $rows[] = $row;
    }
    $result['tables'][] = array(
         'name' = $tableName,
         'data' = $rows
    )
}
print json_encode($result);

Upvotes: 1

Related Questions