很难将这些数组合并。
我希望能够加载多个配置文件并构建一个大型数组,以便能够在我的应用程序中的任何位置调用。
test_config1.php
$config1=array();
$config1['Key1']['AnotherKey1']='Value 1';
$config1['Key2']['AnotherKey1']='Value 2';
$config1['Key3']['AnotherKey1']='Value 3';
return $config1;
test_config2.php
$config2=array();
$config2['Different Key 1']='Different Value 1';
$config2['Different Key 2']='Different Value 2';
$config2['Different Key 3']='Different Value 3';
$config2['Key3']['AnotherKey1']['test']='Test 1';
return $config2;
配置课程:
class Configure
{
public static $configArray = array();
public static function loadConfig($configSource)
{
# Explicitly turn this into an array.
$configSource=(array)$configSource;
# Loop through the array.
foreach($configSource as $configFileName)
{
$config=require_once $configFileName;
self::$configArray[]=$config;
unset($config);
}
return self::$configArray;
}
}
print_r(Configure::loadConfig(array('test_config1.php', 'test_config2.php')));
//print_r(Configure::loadConfig('test_config1.php'));
结果:
Array
(
[0] => Array
(
[Key1] => Array
(
[AnotherKey1] => Value 1
)
[Key2] => Array
(
[AnotherKey1] => Value 2
)
[Key3] => Array
(
[AnotherKey1] => Value 3
)
)
[1] => Array
(
[Different Key 1] => Different Value 1
[Different Key 2] => Different Value 2
[Different Key 3] => Different Value 3
[Key3] => Array
(
[AnotherKey1] => Array
(
[test] => Test 1
)
)
)
)
通缉:
Array
(
[Key1] => Array
(
[AnotherKey1] => Value 1
)
[Key2] => Array
(
[AnotherKey1] => Value 2
)
[Key3] => Array
(
[AnotherKey1] => Value 3
[AnotherKey2] => Array
(
[test] => Test 1
)
)
[Different Key 1] => Different Value 1
[Different Key 2] => Different Value 2
[Different Key 3] => Different Value 3
)
我试过self::$configArray=array_merge(self::$configArray, $config);
,它给出了:
[Key3] => Array
(
[AnotherKey2] => Array
(
[test] => Test 1
)
)
self::$configArray=self::$configArray + $config;
从数组中遗漏$config2['Key3']['AnotherKey2']['test']='Test 1';
。
答案 0 :(得分:1)
尝试此代码(未经测试):
class Configure
{
public static $configArray = array();
public static function loadConfig($configSource)
{
# Explicitly turn this into an array.
$configSource=(array)$configSource;
# Loop through the array.
foreach($configSource as $configFileName)
{
$config=require_once $configFileName;
if (empty(self::$configArray)) {
self::$configArray = $config;
} else {
foreach ($config as $key => $value) {
self::$configArray[$key] = $value;
}
}
unset($config);
}
return self::$configArray;
}
}
更新多个类似的密钥:
class Configure
{
public static $configArray = array();
public static function loadConfig($configSource)
{
# Explicitly turn this into an array.
$configSource=(array)$configSource;
# Loop through the array.
foreach($configSource as $configFileName)
{
$config=require_once $configFileName;
if (empty(self::$configArray)) {
self::$configArray = $config;
} else {
self::$configArray = array_merge_recursive(self::$configArray, $config);
}
unset($config);
}
return self::$configArray;
}
}