PHP:将数组值拆分为键和值[关闭]

I have a txt file which contains:

1:2
2:5
3:10
4:1

I need to be able to add to these numbers. For example I want to add to the last line +5:

1:2
2:5
3:10
4:6

How can I achieve this? I was wondering if the right way was to input the file into an array but I have no idea how to do this as I need to separate the numbers into keys and values, I guess?

The problem as described is pretty generic, but I can do some assumptions to help you.

The initial txt file is basically a key-value store:

1:2
2:5
3:10
4:1

Assuming that the first number is the key, you should tell your algorithm to perform a +x sum to the line with key n.

In (untested & not optimized) php code:

function addToStore($destKey, $numberToSum) {
    $newStore = [];

    foreach(file('store.txt') as $line) {
        list($key, $value) = explode(':', $line);

        if( $key === $destKey) {
            $value += $numberToSum;
        }

        newStore[] = "$key:$value";
    }

    file_put_contents('store.txt', implode("
", $newStore));
}

Then call it as:

addToStore('4', '5');

Something like this:

// get from file
$file = file('file.txt');
$array = [];
foreach ($file as $line) {
    list($column1, $column2) = explode(':', $line);
    $array[(int) $column1] = (int) $column2;
}

// add number
$array[4] += 5;

// save to file
$content = '';
foreach ($array as $column1 => $column2) {
    $content .= $column1 . ":" . $column2 . "
";
}
file_put_contents('file.txt', $content);

However, you must be sure that indexes in first column will be unique because otherwise some rows will be skipped (actually overwritten).

Yes you can add numbers to it when you have it in array form and you can save your text file data in key/value form as given below..

$file_array = array();

$myfile = fopen("yourtextfile.txt", "r") or die("Unable to open file!");

// Read one line until end-of-file

while(!feof($myfile)) {
$line = fgets($myfile);

$line_array = explode(":", $line); // split each line to make array

$file_array[$line_array[0]] = $line_array[1];

}

fclose($myfile); // file_array should be showing you file data into an array

print_r( $file_array );

Hope this helps you!!