【发布时间】: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。