[英]Save data to JSON File in correct format - PHP
我目前正在通過使用以下代碼將點擊坐標保存到JSON文件:
onmouseup = function(e){
var Clicks = {};
Clicks.state = {
cX: e.clientX,
cY: e.clientY,
}
$.ajax({
type : "GET",
url : "PHP/save_json.php",
data : {
state : JSON.stringify(Clicks.state)
}
});
}
<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>
但是,使用上面的代碼,我將坐標保存為以下錯誤格式:
{ “CX”:467, “CY”:374} { “CX”:56, “CY”:474}
誰能幫我將坐標保存在JSON數組中,而不是在單獨的JSON條目中?
我希望文件如下,將坐標添加到文件中已經存在的JSON數組中:
{
"ID":["1","2"],
"cX":["467","56"],
"cY":["374","474"]
}
您需要將數據加載到陣列,添加新數據並保存回文件。
我認為您不需要在字符串中保存數字。 這些代碼將創建新文件(如果不存在)。
<?php
// test input data
if(isset($_GET['state']['cX']) &&
isset($_GET['state']['cY']) &&
is_numeric($_GET['state']['cX']) &&
is_numeric($_GET['state']['cY']) )
{
// ok
} else {
exit('Bad data format');
}
$myFile = __DIR__ . "/JSON/clicks.json";
// step 1, load data from file to array
$array = file_exists($myFile) ?
json_decode(file_get_contents($myFile), true) :
[];
// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];
// step 3, save array back to file
file_put_contents($myFile, json_encode($array));
或者,您可以使用其他可以附加文件的文件格式。 靜態結構化數據的最簡單格式是CSV
您需要做的是:
json_decode
將其轉換為stdClass
的實例。 這將為您提供一個PHP對象,您可以使用常規的PHP函數和語法對其進行修改。 json_decode
。 array_push
將新值從客戶端推送到文件中存儲的數組中(類似於array_push($fileJson->cX, $clientJson->cX);
) json_encode
再次編碼$fileJson
。 這假設clicks.json文件已經使用已創建的數組等正確格式化為JSON。
考慮到key
和value
位的當前排列,很明顯,在將JSON數據寫入文件之前,需要對JSON數據進行某種轉換。 進行此轉換的位置絕對是一個意見問題。 但是,假設您在PHP中收到以下JSON數據:
[{"cX":467,"cY":374},{"cX":56,"cY":474}]
PHP代碼可以寫成(用靜態輸入說明):
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source = json_decode($string, true);
$json_array_target = array();
foreach($json_array_source as $key=>$value){
$json_array_target["ID"][] = $key + 1;
foreach($value as $sub_key => $sub_value){
$json_array_target[$sub_key][] = $sub_value;
}
}
$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);
如果您要echo $transformed_string;
,您會看到:
{"ID":[1,2],"cX":[467,56],"cY":[374,474]}
這將被寫入文件。
使用json_encode將您的字符串轉換為對象,然后使用json_decode和JSON_PRETTY_PRINT選項將其轉換回字符串。
$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.