[英]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.