问题
I have a php.ini
file which contains the following lines:
; ...settings
extension=pdo_mysql
extension=pdo_oci
; settings...
So I do this:
var_dump( parse_ini_file( '/path/to/php.ini' )[ 'extension' ] );
But all I get is string(7) "pdo_oci"
so it looks like the parse simply maintains the final value which extension
was set to.
Is there a way to make the extension
key return an array instead?
I understand that PHP's internals probably use a dedicated parser to explicitly handle this situation so that extensions load properly but that does not help me achieve my goal.
回答1:
Since the keys of the ini file become the keys to the array, the values are overridden. I came up with my own function.
The code:
function my_parse_ini($file){
$arr = array();
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$parsed = parse_ini_string($line);
if(empty($parsed)){ continue; }
$key = key($parsed);
if(isset($arr[$key])){
if(!is_array($arr[$key])){
$tmp = $arr[$key];
$arr[$key] = array($tmp);
}
$arr[$key][] = $parsed[$key];
}else{
$arr[$key] = $parsed[$key];
}
}
fclose($handle);
return $arr;
} else {
// error opening the file.
}
}
Call it passing the file to be parsed, like so:
$parsed = my_parse_ini('/path/to/php.ini');
The result: ($parsed
)
For a file containing
; ...settings
extension=pdo_mysql
extension=pdo_oci
foo=test
bar=ok
foo=teste1
; settings...
This is the output:
Array
(
[extension] => Array
(
[0] => pdo_mysql
[1] => pdo_oci
)
[foo] => Array
(
[0] => test
[1] => teste1
)
[bar] => ok
)
来源:https://stackoverflow.com/questions/47820008/maintain-all-values-of-duplicate-keys-when-parsing-ini-file