我正在获取ini文件的内容,如下所示
$file = 'config.ini';
if (!file_exists($file)) {
$file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);这会产生一个多维数组,但我希望它是一个对象。这在parse_ini_file()中是可能的吗?我将如何做到这一点?
发布于 2015-01-29 08:41:35
您可以使用json_encode()和json_decode()来实现这一点:
$file = 'config.ini';
if (!file_exists($file)) {
$file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);
// convert to data to a json string
$config = json_encode($config);
// convert back from json, the second parameter is by
// default false, which will return an object rather than an
// associative array
$config = json_decode($config);发布于 2015-01-29 08:39:28
如果要将数组转换为stdClass,只需使用以下命令:
$configObj = (object) parse_ini_file($file, true);发布于 2015-01-29 09:02:55
function array_to_object($array, &$object)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$object->$key = new stdClass();
array_to_object($value, $object->$key);
} else {
$object->$key = $value;
}
}
return $object;
}
function arrayToObject($array)
{
$object= new stdClass();
return array_to_object($array, $object);
} $configArr = array(
'NAME' => 'stack over flow',
'AGE' => 28,
'SEX' => 'MALE',
);
$configObj = arrayToObject($configArr);
var_dump($configObj); class stdClass#1 (3) {
public $NAME => string(15) "stack over flow"
public $AGE => int(28)
public $SEX => string(4) "MALE"
}https://stackoverflow.com/questions/28210187
复制相似问题