包括'关键'和'值'属性为json响应

时间:2015-04-05 15:06:47

标签: php mysql json d3.js

查询数据库表,获取数组,并写入json文件。

$sql2 = "SELECT * FROM omharddown ORDER BY id DESC LIMIT 1";
$result2 = mysqli_query($dbc, $sql2);

$json_response = array();

while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
    $row_array 'key:'['ING_SW_CB'] = $row 'value:'['ING_SW_CB'];
    $row_array 'key:'['SB_SW_CB'] = $row 'value:'['SB_SW_CB'];
    $row_array 'key:'['NG3_SW_CB'] = $row 'value:'['NG3_SW_CB'];
    $row_array 'key:'['Mould_Close'] = $row 'value:'['Mould_Close'];
    $row_array 'key:'['Leak_Test'] = $row 'value:'['Leak_Test'];
    $row_array 'key:'['ML_Load'] = $row 'value:'['ML_Load'];
    $row_array 'key:'['Pre_Heat'] = $row 'value:'['Pre_Heat'];
    $row_array 'key:'['Dispense'] = $row 'value:'['Dispense'];
    $row_array 'key:'['A310'] = $row 'value:'['A310'];
    $row_array 'key:'['Gelation'] = $row 'value:'['Gelation'];
    $row_array 'key:'['Platen'] = $row 'value:'['Platen'];
    $row_array 'key:'['Mainline_Unload'] = $row 'value:'['Mainline_Unload'];
    $row_array 'key:'['De_mould'] = $row 'value:'['De_mould'];
    $row_array 'key:'['Clean_Up'] = $row 'value:'['Clean_Up'];
    $row_array 'key:'['Soda_Blast'] = $row 'value:'['Soda_Blast'];
    $row_array 'key:'['Miscellaneous'] = $row 'value:'['Miscellaneous'];

    //push the values in the array
    array_push($json_response,$row_array);
}
    //echo json_encode($json_response);
    $json_data = json_encode($json_response, JSON_PRETTY_PRINT);
    file_put_contents('your_json_file.json', $json_data); 

json文件中的输出是这样的:

[[{"ING_SW_CB":"5","SB_SW_CB":"3",.........}]]

我在寻找的是:

[[{"key":"ING_SW_CB", "value":"5", "key":"SB_SW_CB", "value":3,....}]]

有没有人有解决方案?

我创建了一个使用外部json数据的D3图表。 图表接受y值,但我需要弄清楚如何在x轴上使用类别名称。 用于填充图表的代码。

barData = [];

    d3.json("your_json_file.json", function (data) {

     for (key in data) {
         barData.push(data[key].ING_SW_CB)
         barData.push(data[key].SB_SW_CB)
         barData.push(data[key].NG3_SW_CB)
         barData.push(data[key].Mould_Close)
         barData.push(data[key].Leak_Test)
         barData.push(data[key].ML_Load)
         barData.push(data[key].Pre_Heat)
         barData.push(data[key].Dispense)
         barData.push(data[key].A310)
         barData.push(data[key].Gelation)
         barData.push(data[key].Platen)
         barData.push(data[key].Mainline_Unload)
         barData.push(data[key].De_mould)
         barData.push(data[key].Clean_Up)
         barData.push(data[key].Soda_Blast)
         barData.push(data[key].Miscellaneous)
         // add more .push if needed
     }

1 个答案:

答案 0 :(得分:0)

因此,如果您的数据如下所示:

var current_data = [{
    "ING_SW_CB": "5",
    "SB_SW_CB": "3",
    "NG3_SW_CB": "2",
    "Mould_Close": "8",
    "Leak_Test": "6",
    "ML_Load": "2",
    "Pre_Heat": "1"
}]

...您可以使用d3.entries将其转换为您在评论中提到的格式。尝试:

var formatted_data = d3.entries(current_data[0]);

这会给你:

showing the correct data format in console