gpt4 book ai didi

php - 将数组从 javascript 传递到 PHP 时出错

转载 作者:行者123 更新时间:2023-11-30 10:53:01 25 4
gpt4 key购买 nike

我正在尝试将我的经纬度数组传递给我的 PHP 脚本,以便脚本可以将其保存到 .txt 文件。

我设法序列化我的数组并将其传递给 php 脚本...在 php 端,我设法反序列化它。但是,当我将数组写入文件时,文件仅显示为“数组数组”...而不是值...假设为“(1.3567, 103.124252) (1.3543, 103.436435)”。

下面是我的示例代码(序列化):

function serialize(mixed_value) 
{
var _getType = function( inp ) {
var type = typeof inp, match;
var key;
if (type == 'object' && !inp) {
return 'null';
}
if (type == "object") {
if (!inp.constructor) {
return 'object';
}
var cons = inp.constructor.toString();
match = cons.match(/(\w+)\(/);
if (match) {
cons = match[1].toLowerCase();
}
var types = ["boolean", "number", "string", "array"];
for (key in types) {
if (cons == types[key]) {
type = types[key];
break;
}
}
}
return type;
};
var type = _getType(mixed_value);
var val, ktype = '';

switch (type) {
case "function":
val = "";
break;
case "undefined":
val = "N";
break;
case "boolean":
val = "b:" + (mixed_value ? "1" : "0");
break;
case "number":
val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
break;
case "string":
val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
break;
case "array":
case "object":
val = "a";
var count = 0;
var vals = "";
var okey;
var key;
for (key in mixed_value) {
ktype = _getType(mixed_value[key]);
if (ktype == "function") {
continue;
}

okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
vals += serialize(okey) +
serialize(mixed_value[key]);
count++;
}
val += ":" + count + ":{" + vals + "}";
break;
}
if (type != "object" && type != "array") {
val += ";";
}
return val;
}

PHP(反序列化并粘贴到文件):

$data = $_POST['y'];

$arr = unserialize($data);

$fp=fopen("route.txt","w+");
foreach($arr as $key => $value){
fwrite($fp,$value."\t");
}

感谢您的帮助! :D

最佳答案

  1. 重新发明轮子多少? :) 已经有 JSON明确地出于这个目的,并且有大量的库可以用几乎任何语言对 JSON 进行编码和解码。 PHP 自带 json_decode .
  2. 写入文件时,$value本身就是一个数组。当数组转换为字符串时(输出它是必要的),it'll be cast to the string "Array" .使用 join(',', $value) 输出以逗号分隔的数组的所有值。

关于php - 将数组从 javascript 传递到 PHP 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4221788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com