包括'key'和'value'属性到json响应
问题描述:
Query DB table, fetch array, and write to json file.
$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);
The output in the json file is such:
[[{"ING_SW_CB":"5","SB_SW_CB":"3",.........}]]
What I am looking for is:
[[{"key":"ING_SW_CB", "value":"5", "key":"SB_SW_CB", "value":3,....}]]
Does anyone out there have a solution?
I have created a D3 chart which uses external json data. the chart accepts the y values but I need to fugure out how to use the category names on the x axis. Code to populate chart.
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
}
答
So if you data looks like this:
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"
}]
... you can use d3.entries
to convert it to the format you mention in your comment. Try:
var formatted_data = d3.entries(current_data[0]);
This will give you: