开发者

Modify array values in a file

I have a php file with some arrays in it. I want to modify one of these arrays and write it back to the file. For e.g. say file test.php has contents -

<?php
$arr1 = array("a"=>"b", "c" =>"d");
$arr2 = array("a2" => "b2", "c2" => "d2");

i want to change $arr1 so that test.php now looks like -

<?php
$arr1 = array("a"=>"b", "c" =>"d", "e"=&开发者_如何学JAVAgt;"f");
$arr2 = array("a2" => "b2", "c2" => "d2");

I do not know what arrays are present in the file beforehand.

Edit: i am not adding any variables to the array, only another key value pair. The problem is that the array is part of a file with more arrays in it about which I won't always be aware. I can achieve this if there was only one array in the file, but want to know if it is possible to do this with multiple arrays.


You could introduce another "global" array

$arr = array('arr1' => array("a"=>"b", "c" =>"d"), 'arr2' =>("a2" => "b2", "c2" => "d2"));

and serialize it

$serArr = serialize($arr);
//write to file here

When you read the file, just unserialize its content so you have the "global" array with it's sub-arrays, modify the values you need, serialize it and write it back.

Keep in mind that this can be a huge performance issue when you write big arrays.


If you are within a function (i.e. not in global scope) get_defined_vars() might be a good bet. You'd just need to include the file in a closed scope and return it's keys to get all variable names in the file.


<?php
$arr1 = array("a"=>"b", "c" =>"d");
$newarr=array("d"=>"f");
$arr1+=$newarr;

it's has been 5 years, but i want to give simple way that work for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜