Return 文本文件作为多维数组

Return textfile as multidimensional array


希望一切都好


我使用 php file() 并且效果很好。我只需要在 txt 文件中用一个新行分隔我的 "values",然后 'file()' 将 txt 文件的内容作为一个数组分别提供给我所有值。


我不知道我是否可以将相同的功能进一步实现'key/values'和'多维数组'。如果没有,我有什么其他选项可以将 'text data' 保存在 txt 文件中,然后将其取回多维数组?


目前,我只得到以下信息:

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


如果您知道任何非常简单的解决方案并且可以让我走上正轨,我将不胜感激。

使用 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);

通过这种方式,您可以保留所需的键和值。 JSON encoding/decoding 处理将其作为文本存储在平面文件中的所有痛苦部分。