首页 > 解决方案 > 如何使用脚本硬编码附加到 PHP 文件上的数组?

问题描述

例如,一个 PHP 文件包含以下内容:

<?php

return [
    'sample_array' => [
        'sample_index' => 'sample_data',
    ],
];

我想将值附加到sample_array使用 PHP 脚本。最好的方法是什么?

编辑:运行脚本后,文件应更新为:

<?php

return [
    'sample_array' => [
        'sample_index' => 'sample_data',
        'sample_index2' => 'sample_data2',
    ],
];

编辑:我正在寻找的是创建一个脚本,它将直接更新 PHP 文件的内容以附加数组。

标签: php

解决方案


您可以通过使用var_export(). 然后,您可以将代码存储在具有类似file_put_contents().

// load the array from the file
$arr = include 'file.php';

// modify the array
$arr['sample_array']['sample_index2'] = 'sample data 2';

// write it back to the file
file_put_contents("file.php", "return " . var_export($arr, true) . ";");

给你...

返回数组 (
  'sample_array' =>
  大批 (
    'sample_index' => 'sample_data',
    'sample_index2' => '样本数据 2',
  ),
);

推荐阅读