我一直在試圖解決這個問題,但找不到我能理解的解決方案。遞歸地重命名數組鍵
我有這個數組,當我的應用程序通過讀取動態配置文件加載時,這是在飛行中創建的。
我的問題是,我想要一個名爲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
關於如何處理此問題的任何想法?我覺得我很接近,只需要一個正確的道路上的小指南。
感謝
編輯:更新我的功能,以反映當前attemps
需要更多的休息...看到我下面的評論。 – EthanB