PHP:将数组保存到文件(映射)
Posted
技术标签:
【中文标题】PHP:将数组保存到文件(映射)【英文标题】:PHP: Save Array to file (mapping) 【发布时间】:2015-08-24 14:07:48 【问题描述】:我想通过 POST 将一个数组提供给一个 php 脚本,该脚本应该将该数组保存到一个“地图”文件中。
$data = $_POST["dat"];
for($y = 0; $y < 37; $y++)
for($x = 0; $x < 37; $x++)
$dat .= $data[($y*37)+$x] . ",";
$dat .= "\n";
但是文件是这样的:
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
但我想要这个结果:
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
为什么每行之间有空行??
【问题讨论】:
尝试换掉:$data[($y*37)+$x]
和 trim($data[($y*37)+$x])
var_dump $dat
时有空行吗?换句话说:尝试找出问题是出现在您粘贴的代码中(看起来不像)还是在写入文件时出现。
@Rizier123,工作,请回答,以便我可以标记为已解决
【参考方案1】:
看来您的输入中已经有了一些换行符。要简单地删除它们,只需使用trim()
,例如
$dat .= trim($data[($y*37)+$x]) . ",";
//^^^^^ See here
【讨论】:
对不起,我不明白,这怎么可能是一个解决方案?如果他在输入中有新行,则行将在中间逗号之前的某处断开,并在以逗号开头正下方有一个新行。这不是我在 OP 的示例中看到的。 @rlanvin 为什么他们需要在逗号之前的中间?它们可以在任何地方,但 OP 在模式中有它们,因此在第一行之后,他在彼此的新输入行中都有一个新行。 输入后用逗号连接。如果您的输入包含您所建议的“0\n”,则结果字符串应为“0\n”,因此您会看到一个换行符,然后在下一行的开头看到一个逗号。 没错,这可以解释。但反过来更常见,它必须恰好是每 37 个输入,而不是其他任何地方。好吧,为什么不...感谢您的发现。以上是关于PHP:将数组保存到文件(映射)的主要内容,如果未能解决你的问题,请参考以下文章