html - How does PHP modify a certain value of the array content in a file or...?
迷茫
迷茫 2017-07-03 11:40:50
0
2
846

I have been confused about this question for a long time. I hope someone can give me some advice.

If the content in config.php is:

 '111111', 'k2' => '222222', 'k3' => '333333', );

or it could be:

{ "k1": "111111", "k2": "222222", "k3": "333333", }

How should I modify the value under 'k1'? How can I achieve this without using str_replace? (Because the value of 'k1' is not fixed, the method I want is to find the key, then modify the value of the key and save the file)

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all (2)
大家讲道理

The first one is easier to do, but the second one should be checked first to see if it is written correctly. This structure is similar to a JSON object but not, so it is not easy to do.
The first method

include '....'; // 此处为文件名 // 下面只是示例,随便怎么操作$config['hello'] foreach($config['hello'] as $key => $value) { ... } $output = "$config['hello'] = " . var_export($config['hello'], TRUE); file_put_contents('....', $output); // 省略号处为原来的文件名

Mainly usevar_exportto output an array that can be read by PHP. When the second parameter of this function isfalse, it will be output directly. When it istrue, the result will be returned to the variable.
One thing that needs to be reminded is that the array layout generated by this function is not very good-looking. If you mind, just write one yourself.

Update

Modify the example code ofk1

include '....'; $config['hello']['k1'] = 'aaaa'; $output = "$config['hello'] = " . var_export($config['hello'], TRUE); file_put_contents('....', $output);
    漂亮男人

    In fact, the easiest way is not to write the config file like this. The config file format is generally as follows:

     '111', 'k2' => '222', 'k3' => '333' ];

    External files can directly assign the value of the array to a variable by requiring the file, such as

    $config = require 'config.php';

    It’s easy to get and change values, and it’s also easy to write back to files.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!