[英]PHP how do i write a multi dimmensional array into file
I am trying to use files to hold an array for checkers 我正在尝试使用文件来保存检查程序数组
this is the array 这是数组
$board = array(
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0)
);
while also giving the values so that i can set the beginning of the board with the pieces placed in a predefined positions to start the game in then have them user input which location they want to move the pieces into 同时提供值,以便我可以将棋子放置在预定位置来设置棋盘的开始位置,以开始游戏,然后让用户输入他们要将棋子移动到的位置
I already have this while loop 我已经有这个while循环
$row = 0;
print "<form>";
print "<table border = 1>";
while ($row < 8){ // Counts to 8. (from 0...7 = 8 times. 0 ... 8 = 9 times)
print "<tr>";
$row++;
$col = 0; // reset column to 0 each time printing one row.
while ($col < 8){
print "<td>";
if($Board[$row][$col] == 0)
{
$value=$row.$col;
print "<input type=\"checkbox\" name=\"box[]\" value=\"$value\">";
// Add \ before " otherwise it will treat as the end of the quote.
}
print "</td>";
$col++;
}
print "</tr>";
}
print "</table>";
print "</form>";
} }
file_put_contents($f, serialize($board));
this will serialize your multidimensional array in a file. 这会将您的多维数组序列化到文件中。
To read it back, use 要读回,请使用
$board = unserialize(file_get_contents($f));
2 variants: using serialize 2个变体:使用序列化
#dump:
file_put_contents('file_name', serialize($board));
#restore:
$board=unserialize(file_get_contents('file_name'));
using JSON: 使用JSON:
#dump:
file_put_contents('file_name', json_encode($board));
#restore:
$board=json_decode(file_get_contents('file_name'));
JSON variant works faster, but can dump only simple structures (strings, arrays, numbers). JSON变体的运行速度更快,但只能转储简单的结构(字符串,数组,数字)。 serialize can dump objects too but works slower and generate more output
序列化也可以转储对象,但工作速度较慢并生成更多输出
Why serialize and store ? 为什么要序列化和存储? Even you can directly print array to file
即使您可以直接将数组打印到文件
ob_start(); ob_start();
print_r( $yourArry); print_r($ yourArry);
$output = ob_get_clean(); $输出= ob_get_clean();
file_put_contents( 'yourfilename.txt',$output ); file_put_contents('yourfilename.txt',$ output);
See example here http://www.my-php-scripts.net/index.php/Array-Scripts/php-write-multidimensional-array-into-file-advanced-php.html 在此处查看示例http://www.my-php-scripts.net/index.php/Array-Scripts/php-write-multiDimension-array-into-file-advanced-php.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.