Writing to JSON with PHP


Writing to JSON with 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); 

我需要关键字"键"&"value"添加到输出中,这样我就可以弹出一个D3图表。

您需要对行的结果进行循环并构建更多的数组:

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

在列上循环:

$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);
$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);