2015-04-06 66 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