在多维数组中,'@attributes'数组出现在数组中不同维度的许多不同节点上。
每当发生'@attributes'数组时,如何将'@attributes'数组的所有节点移动到其父数组中,同时取消设置'@attributes'数组?
Array
(
[@attributes] => Array
(
[Id] => 1
[Updated] => yes
)
[Country] => Germany
[City] => Munich
[Inhabitants] => Array
(
[0] => Array
(
[@attributes] => Array
(
[Id] => 1
[type] => private
)
[LastName] => Mayer
[FirstName] => Georg
)
[1] => Array
(
[@attributes] => Array
(
[Id] => 2
[type] => private
)
[LastName] => Stein
[FirstName] => Adam
)
)
)
这里有一个类似的帖子(php move nodes to parent array),但@prodigitalson提供的解决方案不适用于上面的多维数组。
编辑:该数组摘自API的XML响应。我正在使用以下代码提取相关内容
$reader = new XMLReader();
$reader->open($file);
while($reader->read()) {
if($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Country') {
$doc = new DOMDocument('1.0', 'UTF-8');
$doc = $doc->importNode($reader->expand(),true);
$xml = simplexml_import_dom($doc);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
//move nodes of the '@attributes' array into parent array (prodigitalson's solution from https://stackoverflow.com/questions/3694138/php-move-nodes-to-parent-array)
foreach($array as $key => $values) {
if(isset($values['@attributes'])) {
$a[$key] = array_merge($a[$key], (array) $values['@attributes']);
unset($a[$key]['@attributes']);
}
}
echo '<pre>'.print_r($array, true).'</pre>';
}
}
但是,这对数组没有任何作用(即使它在原始帖子中有效)并且我在过去几个小时内没有运行它。