我一直在尝试自己解决这个问题,但找不到我能理解的解决方案。
当我的应用程序通过读取动态配置文件加载时,我有一个动态创建的数组。
我的问题是我想要一个名为的数组,该数组alias
将被拾取并重命名其['@attr']
下的父数组。这是一个例子来说明我的意思。
[database] => Array
(
[0] => Array // Would be renamed to "production"
(
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => test
[@attr] => Array
(
[alias] => production
[name] => live
)
)
[1] => Array // Would be renamed to "development"
(
[user_data] => Array
(
[0] => Array // Would be renamed to "three"
(
[user] => sample
[@attr] => Array
(
[alias] => three
)
)
[1] => Array // Would be renamed to "two"
(
[user] => sample
[@attr] => Array
(
[alias] => two
)
)
)
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => test
[@attr] => Array
(
[alias] => development
)
)
)
到目前为止,这是我的代码
private function _applyXmlAlias($array)
{
foreach ($array as $config)
{
if (is_array($config))
{
if (isset($config['@attr']['alias']))
{
$alias = $config['@attr']['alias'];
unset($config['@attr']['alias']);
if (empty($config['@attr']))
{
unset($config['@attr']);
}
$this->_alias[$alias] = $config;
break;
//$this->_temp = reset();
} else {
$this->_applyXmlAlias($config);
}
}
}
}
如果我对我的_alias
财产进行 print_r,我会得到这个
Array
(
[production] => Array
(
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => 3306
[@attr] => Array
(
[name] => live
)
)
[development] => Array
(
[user_data] => Array
(
[0] => Array
(
[user] => sample
[@attr] => Array
(
[alias] => three
)
)
[1] => Array
(
[user] => sample
[@attr] => Array
(
[alias] => two
)
)
)
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => 3306
)
)
注意:我不确定为什么我的循环只捕获带有键的最后一个嵌套数组,alias
而不是具有值的其他键production
和development
关于如何解决这个问题的任何想法?我觉得我很接近,只需要在正确的道路上得到一点指导。
谢谢
编辑:更新了我的功能以反映当前的尝试