【问题标题】:Remove specific value from ini file从ini文件中删除特定值
【发布时间】:2019-06-10 16:10:01
【问题描述】:

我有一个如下所示的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'); 调用函数。 不知道发生了什么或为什么它要删除的不仅仅是名为“jack”的项目,可以使用一些见解。谢谢!

【问题讨论】:

  • 如果array_search返回false怎么办?
  • 啊是的,可以做到。
  • 你知道你可以使用color[]=red color[]=blue color[]=orange,但最好使用JSON。

标签: php ini


【解决方案1】:
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);
}

【讨论】:

    猜你喜欢
    • 2016-07-29
    • 2019-08-17
    • 2015-03-14
    • 1970-01-01
    • 2013-07-13
    • 2012-05-21
    • 1970-01-01
    • 2018-08-31
    • 2018-10-08
    相关资源
    最近更新 更多