Удалить конкретное значение из INI-файла - PullRequest
1 голос
/ 10 июня 2019

У меня есть INI-файл, как показано ниже

[PeopleA]
names=jack, tom, travis
color=red, blue, orange
[PeopleB]
names=sam, chris, kyle
color=purple, green, cyan

Цель - получить определенное значение и удалить его с помощью PHP

Мой код:

remove_ini($file, 'PeopleA', 'names', 'jack'); // call function
function remove_ini($file, $section, $key, $value) {
    $config_data = parse_ini_file($file, true);
    $raw_list = $config_data[$section][$key];
    $list = explode(", ", $raw_list);
    $index = array_search($value, $list);
    unset($list[$index]); //remove from list
    $config_data[$section][$key] = ''; // empty config_data
    foreach($list as $list_item){ // re-iterate through and add to config_data w/o val passed in
        if (empty($config_data[$section][$key])) {
            $config_data[$section][$key] = $list_item;
        } else {
            $config_data[$section][$key] .= ', ' . $list_item;
        }    
    }
    $new_content = '';
    foreach ($config_data as $section => $section_content) {
        $section_content = array_map(function($value, $key) {
            return "$key=$value";
        }, array_values($section_content), array_keys($section_content));
        $section_content = implode("\n", $section_content);
        $new_content .= "[$section]\n$section_content\n";
    }
    file_put_contents($file, $new_content);
}

Похоже, что это происходит при первом запуске, но после этого он начинает удалять оставшиеся значения.

Я просто вызываю функцию с помощью remove_ini($file, 'PeopleA', 'names', 'jack');. Не уверен, что происходит или почему он удаляет больше, чем предметы с именем «Джек», может использовать некоторую проницательность. Спасибо!

1 Ответ

1 голос
/ 10 июня 2019
remove('file.ini', 'PeopleA', 'names', 'travis');

function remove($file, $section, $key, $value, $delimiter = ', ')
{
    $ini = parse_ini_file($file, true);

    if (!isset($ini[$section]) or !isset($ini[$section][$key]))
    {
        return false;
    }


    $values = explode($delimiter, $ini[$section][$key]);
    $values = array_diff($values, [$value]);
    $values = implode($delimiter, $values);

    if ($values)
    {
        $ini[$section][$key] = $values;
    }
    else
    {
        unset($ini[$section][$key]);
    }


    $output = [];

    foreach ($ini as $section => $values)
    {
        $output[] = "[$section]";

        foreach ($values as $key => $val)
        {
            $output[] = "$key = $val";
        }
    }

    $output = implode(PHP_EOL, $output);

    return file_put_contents($file, $output);
}
...