MySQL到JSON,如何获得正确的格式?

时间:2016-06-19 16:48:54

标签: php mysql json

所以,我使用PHP脚本将MySQL输出到JSON,但我无法弄清楚如何输出正确的JSON格式。

这是PHP脚本:

$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');

以下是输出的JSON格式:

[{
    "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"
}]

这是我想要的JSON格式:

{
    "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]
    ]
}

1 个答案:

答案 0 :(得分:1)

解决方案是这样的:

  • 创建两个数组$columns$data
  • $columns数组中,存储位置和关联的字段名称
  • $data数组中,使用while循环插入所有数据行。
  • 最后,在$result数组中插入两个数组,然后在其上应用json_enocde()

以下是代码:

// 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  
}   

注意:不要使用mysql_*函数,从PHP 5.5开始不推荐使用它们,并且在PHP 7.0中完全删除它们。请改用mysqlipdoAnd this is why you shouldn't use mysql_* functions