Adam Dedanga Adam Dedanga - 5 months ago 8
JSON Question

MySQL to JSON, how to get the right format?

So, I'm using a PHP-script to output MySQL to JSON, but I'm having trouble figuring out how to output the right JSON-format.

Here's the PHP-script:

$sql_query = "SELECT * FROM DiseaseData";
$res_sql = mysql_query($sql_query) or die(mysql_error());
$arr = array();


if(mysql_num_rows($res_sql) > 0){

ini_set('memory_limit', '-1');
while($row_sql = mysql_fetch_assoc($res_sql)){

$arr[] = $row_sql;

}
$json = json_encode($arr);
$file = '../../files/json/DiseaseData.json';
file_put_contents($file, $json);

}
ini_set('memory_limit', '-1');


Here's the outputted JSON-format:

[{
"ID": "1",
"Magnitude": "0.842",
"County": "Alameda",
"Disease": "E. coli O157",
"lat": "37.7652",
"lng": "-122.242"
}, {
"ID": "2",
"Magnitude": "1.520",
"County": "Alameda",
"Disease": "HIV",
"lat": "37.7652",
"lng": "-122.242"
}]


This is the JSON-format I'd like to have it in:

{
"columns":[{
"fieldName" : "ID",
"position" : 1
},
{
"fieldName" : "Magnitude",
"position" : 2
},
{
"fieldName" : "County",
"position" : 3
},
{
"fieldName" : "Disease",
"position" : 4
},
{
"fieldName" : "lat",
"position" : 5
},
{
"fieldName" : "lng",
"position" : 6
},]
"data": [
[ 1, 0.842, "Alameda", "E. coli O157", 37.7652, -122.242],
[ 2, 1.520, "Alameda", "HIV", 37.7652, -122.242]
]
}

Answer

The solution would be like this:

  • Create two arrays, $columns and $data
  • In $columns array, store the position and the associated field name
  • In $data array, insert all data rows using while loop.
  • Finally, insert both the arrays in $result array and then apply json_enocde() on it.

Here's the code:

// your code

if(mysql_num_rows($res_sql) > 0){   
    $columns = $data = array();
    $max_columns = mysql_num_fields($res_sql);

    for($i=0; $i < $max_columns; $i++){
         $columns[] = array('fieldName' => mysql_field_name($res_sql, $i), 'position' => $i+1);
    }

    while($row_sql = mysql_fetch_assoc($res_sql)){
        $data[] =  array_values($row_sql);
    }
    $result = array('columns' => $columns, 'data' => $data);
    $json = json_encode($result);

    // your code  
}   

Note: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Comments