Can you please tell me how I can save a two dimensional array in to a text file
if I have an array with unknown number of elements in its index value:
$two_darray[unknown][unknown];
Can you please tell me how I can save a two dimensional array in to a text file
if I have an array with unknown number of elements in its index value:
$two_darray[unknown][unknown];
You simply need to serialize this array. You can wrap it in serialize()
and output this to a file. You can then use unserialize()
later to decode it.
For portability, I recommend using JSON instead, with json_encode()
/json_decode()
.
file_put_contents('someFile.json', json_encode($yourArray));
Actually, @Brad's and @Hilmi's answers are correct, but I'm not sure using only JSON is a good advice.
You can choose
JSON
write: file_put_contents('someFile.json', json_encode($two_darray));
read: $two_darray = json_decode(file_get_contents('someFile.txt'));
XML
Look this answer
Serialized data
write: file_put_contents('someFile.txt', serialize($two_darray));
read: $two_darray = unserialize(file_get_contents('someFile.txt'));
CSV (to use with MS Excel or some DB)
$handler = fopen('someFile.csv', 'w+');
foreach ($two_darray as $one_darray) {
fputcsv($handler, $one_darray);
}
read it with fgetcsv
and even SQLite
$db = new SQLiteDatabase('someFile.sqlite');
foreach ($two_darray as $one_darray) {
$db->query("INSERT INTO `MyTable` VALUES (".implode(',', $one_darray).")");
}
read: $two_darray = $db->sqlite_array_query("SELECT * FROM MyTable");
EDIT Binary (for .zip or .tar.gz)
Try pack()
You can serialize the array to a string and save it into the file, and when ever you want that array just by unserializing the file's content you'll have the array back
<?php
$arr = array( array('aa', 'aa'), array('bb','bb') );
file_put_contents('/tmp/test',serialize($arr));
var_dump(unserialize(file_get_contents('/tmp/test')));
?>
You can also use json_encode/json_decode instead of serialize/deserialize as suggested by @Brad above