如何重命名比找到的键高两级的键,以此数组为例
[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']);
}
reset($config);
while (list($key, $val) = each($config))
{
$this->_config[$alias][$key] = $val;
}
//$this->_config[$alias] = $config;
//$this->_applyXmlAlias($this->_alias[$alias]);
} else {
$this->_applyXmlAlias($config);
}
} else {
break;
}
}
}
我得到了这个数组输出
Array
(
[database] => Array
(
[0] => Array
(
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => test
[@attr] => Array
(
[alias] => production
[name] => live
)
)
[1] => 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] => test
[@attr] => Array
(
[alias] => development
)
)
)
[production] => Array
(
[host] => test
[user] => test
[pass] => test
[name] => test
[port] => test
[@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] => test
)
[three] => Array
(
[user] => sample
)
[two] => Array
(
[user] => sample
)
)
正如你所看到的,我有点得到了我的输出。唯一的问题是我需要用主配置数组中的新alias
名称替换新数组。并且还需要让数组知道包含键[@attr][alias]
的任何子数组,它们属于同一个父数组,而不是附加到主配置数组。
任何想法?
答案 0 :(得分:0)
据我从你的问题陈述中理解,你需要寻找一个基于递归/堆栈的解决方案。但这既昂贵又复杂。 如果您可以描述您需要执行此操作的方案,可能会通过讨论发挥更好的设计:)