从字面上看,将二进制数据写入文件

Write binary data to file, literally

我有一个整数数组

Array
(
    [0] => Array
        (
            [0] => 1531412763
            [1] => 1439959339
            [2] => 76
            [3] => 122
            [4] => 200
            [5] => 4550
            [6] => 444
        )
...

等等,我想如果我把它看成一个数据库——最外层数组的元素是行,内部数组的元素是列。

我想将该信息保存到一个文件中,以便以后能够检索它,但我想将其保存为二进制数据以保存 space。基本上,如果我将示例 1531412763 中的第一个整数写入文件,它将占用 10 个字节,但如果我可以将其保存为有符号整数,它将占用 4 个字节。

我看了很多其他的答案,都建议使用 fwrite,但我不明白如何以这种方式使用?

要将二进制数据写入文件,您可以使用函数pack() and unpack()。 Pack 将产生一个二进制字符串。由于结果是一个字符串,您可以将整数连接成一个字符串。然后将此字符串作为一行写入您的文件。

这样您就可以轻松地使用 file() 阅读,这会将文件放入一个行数组中。然后每行 unpack(),你就得到了原来的数组。

像这样:

$arr = array(
    array ( 1531412763, 1439959339 ),
    array ( 123, 456, 789 ),
);

$file_w = fopen('binint', 'w+');

// Creating file content : concatenation of binary strings 
$bin_str = '';
foreach ($arr as $inner_array_of_int) {
    foreach ($inner_array_of_int as $num) {
        // Use of i format (integer). If you want to change format
        // according to the value of $num, you will have to save the
        // format too.
        $bin_str .= pack('i', $num);
    }

    $bin_str .= "\n";
}

fwrite($file_w, $bin_str);
fclose($file_w);


// Now read and test. $lines_read will contain an array like the original.
$lines_read = [];
// We use file function to read the file as an array of lines.
$file_r = file('binint');

// Unpack all lines
foreach ($file_r as $line) {
    // Format is i* because we may have more than 1 int in the line
    // If you changed format while packing, you will have to unpack with the
    // corresponding same format
    $lines_read[] = unpack('i*', $line);
}

var_dump($lines_read);