Search code examples
phparraysdatabasemultidimensional-arraydocument-storage

Return textfile as multidimensional array



Hope everything is good.


I use php file() and it works very well. I only need to separate my "values" in the txt-file with a new row, and then 'file()' will give me the contents of the txt-file as an array with all the values separately.


I do not know if I can take the same function one step further to achieve 'key/values' and 'multidimensional arrays'. If not, what do I have for other options to be able to save 'text data' in a txt file and then get it back in a multidimensional array?


At the moment, I only get the following:

[0] => 'value1',
[1] => 'value2',
[2] => 'value3',


If you know any solutions that are very straightforward and can put me on the right track here, I am very grateful.


Solution

  • A simple primer for doing this with JSON:

    // example array of data
    $myarray = array();
    $myarray[] = ['name' => 'value 1','age' => '31','city' => 'nowhere'];
    $myarray[] = ['name' => 'value 2','age' => '12','city' => 'somewhere'];
    $myarray[] = ['name' => 'value 3','age' => '67','city' => 'anywhere'];
    print_r($myarray);
    
    // to save your array to a file
    file_put_contents('/path/to/file.json',json_encode($myarray));
    
    // now to retrieve:
    $myarray = json_decode(file_get_contents('/path/to/file.json'),true);
    print_r($myarray);
    

    By doing it this way, you retain those keys you want, and the values. The JSON encoding/decoding handles all the painful bits of storing it as text in a flatfile.