Recommended sites
Web Hosting Reviews

Storing multidimensional arrays in a file

In this tutorial I will show you how to store a multidimensional array in a file and how to retrieve these data. With this method you can imitate a very basic database functionality.

Storing multidimensional arrays in a file

In this tutorial I will show you how to store a multidimensional array in a file and how to retrieve these data. With this method you can imitate a very basic database functionality.

Step 1.
To realize this we need to implement 2 methods. One for the storing array and one which reads the file back and create an array from its content. The most important part is how to convert an array into a format which can be store easy in a file. To do this first we convert the array into a special string format. In this format we use some special characters to separate various sub-arrays and data elements. After it the saving of this string is quite easy.

So let's try to convert the array into a special string. So I create a new function called array2string() and this function has 3 parameters. They are input array, the output string and a helper variable to store actual key value. This helper variable for the key element will be important later. In case of the last 2 parameters we will use variable references as we will call our function in a recursive way.

The theory is that we create a for each loop on the main array. If the actual data itself is again a new sub-array then the function will call itself. In this case that input array will be the actual sub-array. In case of the actual value is not an other array then we will add this data to the output string in the corresponding key-value format.

The complete code is quite short:

<?php
   
function array2string($myarray,&$output,&$parentkey){
      foreach(
$myarray as $key=>$value){
         if (
is_array($value)) {
            
$parentkey .= $key."^";
            
array2string($value,$output,$parentkey);
            
$parentkey = "";
         }
         else {
            
$output .= $parentkey.$key."^".$value."\n";
         }
      }
   }

?>


Don't forget about the separator character. Select one which is not causes any problem. Now this string can be easily stored in a file. See it in a later step.

Step 2.
Now it's time to make the reverse function as well. Let's call it to string2array() and it needs 2 parameters. The input string which we want to convert and an array reference which will store the resulted array. First we need to divide the input string into smaller parts using the explode() function and our main separator character. After it we iterate over the resulted list and analyze it line by line. Inside this loop we divide the actual line it smaller parts again. If there is no more possibilities to divide the string even smaller values then we will add the actual value to the corresponding array element after we created that.

At the end our code looks like this:

<?php
   
function string2array($string,&$myarray){
      
$lines = explode("\n",$string);
      foreach (
$lines as $value){
         
$items = explode("&#183;",$value);
         if (
sizeof($items) == 2){
            
$myarray[$items[0]] = $items[1];
         }
         else if (
sizeof($items) == 3){
            
$myarray[$items[0]][$items[1]] = $items[2];
         }
      }
   }
?>


Step 3.
As we have both important functions implemented let's see an example how it works in the real life.
First I have created some test data. You can use this:

<?php
   
// Create some test data
   
$mydb[0]['name'] = "John";
   
$mydb[0]['city'] = "Boston";
   
$mydb[0]['age']  = "32";
   
$mydb[1]['name'] = "Max";
   
$mydb[1]['city'] = "London";
   
$mydb[1]['age']  = "41";
   
$mydb[2]['name'] = "Ann";
   
$mydb[2]['city'] = "Bonn";
   
$mydb[2]['age']  = "29";
   
$mydb[3]['name'] = "Peter";
   
$mydb[3]['city'] = "Dallas";
   
$mydb[3]['age']  = "28";
   
$mydb[4]['name'] = "Martin";
   
$mydb[4]['city'] = "Berlin";
   
$mydb[4]['age']  = "22";
?>


Now we just need to call our implemented array2string() function and store the output string in a text file.

<?php
   
// Convert the array into string
   
array2string($mydb,$output,$parent);
   
   
// Store the string in a file   
   
$f1 = fopen("test.txt","w+");
   
fwrite($f1,$output);
   
fclose($f1);
?>


To read it back makes no problem.

<?php
   
// Read the file back from the disk
   
$f1 = fopen("test.txt","r");
   
$newString = fread($f1,filesize('test.txt'));
   
fclose($f1);
   
   
// Convert the content back to an array
   
string2array($newString, $newArray);

   
// Print out the array
   
foreach ($newArray as $item) {
      echo 
'Name: '.$item['name'].'<br/>';
      echo 
'City: '.$item['city'].'<br/>';
      echo 
'Age: '. $item['age'].'<br/>';
   }
?>


That's it!

Download:
You can download an ArrayHandler script in the Download -> Conversion tools -> ArrayHandler.

Sponsored links