查詢數據庫表,獲取數組並寫入json文件。將'key'和'value'屬性包含到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
}
你想要的格式是無效的,因爲你將有多個'key'並在同一個對象,這是不可能的'value'鍵。它需要採用當前格式或者[[{「key」:「ING_SW_CB」,「value」:「5」},{「key」:「SB_SW_CB」,「value」:3,... 。}]]' – Sean 2015-04-05 15:12:04
爲什麼你想要這種格式的JSON?您正在有效地移除鍵與其值之間的關聯,並計算不同鍵/值對的順序以重新建立鍵。 – dartonw 2015-04-05 15:14:35
我在D3中創建了一個圖表,並需要從外部json文件中填充數據。我見過的最好的例子使用了類似的格式。 – 2015-04-05 15:18:00