从外部文件替换数组中的键并将其写回

时间:2017-01-25 20:51:23

标签: php arrays file replace file-get-contents

我在文件中有一个数组,我想从中更改一个值并将其写回原始文件中的文件。

我的数组文件:

return [
    'modules' => [
        'test-module1'      => 1,
        'test-module2'      => 1,
    ],
];

我想替换一个值(数字)并将它像这样的样式写回到PHP文件中(如果可能的话)。

E.g。我想停用test-module1并将密钥设置为0。什么是最好的方法。我现在没有计划。

编辑:我知道如何更改密钥,但我不知道如何将密码写回文件。

1 个答案:

答案 0 :(得分:2)

我是用JSON做的。但是,如果您与此格式绑定,则返回一个数组。只需包含,修改和写入:

$result = include('path/to/file.php');
$result['modules']['test-module1'] = 0;

但要获得这种格式很难。你会得到var_export()的其他数组格式:

file_put_contents('path/to/file.php', 'return ' . var_export($result, true) . ';');    

收率:

return array (
  'modules' =>
  array (
    'test-module1' => 0,
    'test-module2' => 1,
  ),
);

但是,json_encode($result, JSON_PRETTY_PRINT);会产生:

{
    "modules": {
        "test-module1": 0,
        "test-module2": 1
    }
}

然后您可以从那里使用file_get_contents()json_decode()。无需return