0

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];
Learner_51
  • 1,075
  • 3
  • 22
  • 38

4 Answers4

4

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));
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 1
    @Orangepill, Excellent point. One other thing I forgot to mention that might influence the decision... if you need native PHP types, you will need PHP's serialization. – Brad Jul 22 '13 at 03:30
  • 1
    and for non-native classes make sure you have definitions included or an autoloader in play prior to calling unserialize or you will end up with a bunch of incomplete class objects. – Orangepill Jul 22 '13 at 03:32
3

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()

Community
  • 1
  • 1
vladkras
  • 16,483
  • 4
  • 45
  • 55
  • thats a nice explanation. Can you please show us how you read the value back in to an array using JSON and Serialized methods – Justin k Jul 22 '13 at 04:17
0

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

Hilmi
  • 3,411
  • 6
  • 27
  • 55
0
<?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

spats
  • 805
  • 1
  • 10
  • 12