<?php $bookshelf = array( array( array( 'author' => 'Л. Толстый', 'title' => 'Война и пир', 'year' => 2005, ), array( 'author' => 'Н. Гоголь-Моголь', 'title' => 'Мертвые уши', 'year' => 2005, ), ), array( array( 'author' => 'Г. Велс', 'title' => 'Машина Бремени', 'year' => 2009, ), array( 'author' => 'Э. Дерроуз', 'title' => 'Нарзан', 'year' => 1994, ), ), ); $bookshelf[] = 'SuperPuper'; object2file($bookshelf, 'array.txt'); 

It is necessary to write to the file and read from the file of this array, I'm just learning.

    1 answer 1

     $filename = 'array.txt'; // Запись. $data = serialize($bookshelf); // PHP формат сохраняемого значения. //$data = json_encode($bookshelf); // JSON формат сохраняемого значения. file_put_contents($filename, $data); // Чтение. $data = file_get_contents($filename); //$bookshelf = json_decode($data, TRUE); // Если нет TRUE то получает объект, а не массив. $bookshelf = unserialize($data); 
    • one
      json_encode / json_decode for better compatibility? - E_p
    • @E_p, thanks for the addition. The choice between serialize() and json_encode() depends on many factors, but serialize() more generic to PHP. - Alex Zhulin
    • If the “big” array, for example, occupies 20M in memory, and PHP has a limit on the amount of used memory, for example, 32M, then the intermediate variable $ data can cause an error 500. It would be interesting to solve without $ data. - user239133
    • @ Ruslan, yes, but before that you need to serialize the data anyway. From the situation with the file is not particularly different. Postgres or SQLite, at least at the C API level, provide something like file descriptors for BLOB fields. - user239133
    • @Alexander Zonov you are right, I screwed up ... - Ruslan