簡體   English   中英

PHP如何將多維數組寫入文件

[英]PHP how do i write a multi dimmensional array into file

我正在嘗試使用文件來保存檢查程序數組

這是數組

$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循環

      $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));

這會將您的多維數組序列化到文件中。

要讀回,請使用

$board = unserialize(file_get_contents($f));

2個變體:使用序列化

#dump:
file_put_contents('file_name', serialize($board));
#restore:
$board=unserialize(file_get_contents('file_name'));

使用JSON:

#dump:
file_put_contents('file_name', json_encode($board));
#restore:
$board=json_decode(file_get_contents('file_name'));

JSON變體的運行速度更快,但只能轉儲簡單的結構(字符串,數組,數字)。 序列化也可以轉儲對象,但工作速度較慢並生成更多輸出

為什么不序列化數組並將其作為字符串存儲到文件中。 為了找回數組,您可以從文件中讀取字符串並將其反序列化。 這里閱讀

為什么要序列化和存儲? 即使您可以直接將數組打印到文件

ob_start();

print_r($ yourArry);

$輸出= ob_get_clean();

file_put_contents('yourfilename.txt',$ output);

在此處查看示例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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM