2015-04-06 63 views
0

我需要幫助我的JSON輸出。目前我的輸出是這樣:用PHP寫入JSON

[ 
    [ 
    { 
     "ING_SW_CB": "5", 
     "SB_SW_CB": "3", 
     "NG3_SW_CB": "1", 
     "Mould_Close": "4", 
     "Leak_Test": "5", 
     "ML_Load": "6", 
     "Pre_Heat": "3", 
     "Dispense": "9", 
     "A310": "7", 
     ............ 
    } 
    ] 
] 

我想它是與「鑰匙」 &「值」包含在輸出以下。

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

她的是我的PHP腳本:

$json_response = array(); 

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

    //push the values in the array 
    array_push($json_response,$row_array); 
} 

$json_data = json_encode($json_response, JSON_PRETTY_PRINT); 
file_put_contents('your_json_file.json', $json_data); 

我需要 「鑰匙」 & 「值」 添加到輸出的關鍵字,這樣我就可以popuate一個D3圖。

回答

3

您需要在該行的業績環和建造更多的數組:

while(...) { 
    $temp = array(); 
    foreach($row as $key => $value) { 
     $temp[] = array('key' => $key, 'value' => $value); 
    } 
    $json_response[] = $temp; 
} 
+0

謝謝你馬克,我要去給這旋轉! –

+0

出於某種原因,Marc未創建'your_json_file.json'。我沒有收到錯誤查詢,但文件沒有寫入。 –

+0

檢查file_put_contents的返回值。如果它的布爾值爲false,那麼就有錯誤。 –

0
$json_response = array(); 

while ($row = mysqli_fetch_array($result2, MYSQL_ASSOC)) { 


//push the values in the array 

foreach($row as $k=>$v){ 
     $my_array = array("key"=>$k, "value"=>$v); 
} 

    array_push($json_response,$my_array); 
} 



$json_data = json_encode($json_response, JSON_PRETTY_PRINT); 
file_put_contents('your_json_file.json', $json_data); 
+0

你錯過了'key'和'value'屬性。 – Barmar

+0

並且每次通過內部循環覆蓋'$ my_array'。 – Barmar

+0

嗨MrTechie,當我使用你的方法時,返回給我的是所有的「雜項」coulumns與他們的價值觀。其他列不顯示在我的外部json文件中。 –

1

環比列:

$json_response = array(); 
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) { 
    $json_row = array(); 
    foreach ($row as $key => $value) { 
     $json_row[] = array('key' => $key, 'value' => $value); 
    } 
    $json_response[] = $json_row; 
} 
$json_data = json_encode($json_response, JSON_PRETTY_PRINT); 
file_put_contents('your_json_file.json', $json_data); 
+0

謝謝你,Barmar,我要改變代碼,我會讓你知道我如何繼續,歡呼。 –

+0

由於某些原因Barmar'your_json_file.json'未被創建。我沒有收到錯誤查詢,但文件沒有寫入。 –

+0

也許您沒有該文件夾的寫入權限。檢查你的PHP錯誤日誌中的細節。 – Barmar