In a multidemensional array, the '@attributes' array occurs at many different nodes across different dimensions within the array.
Whenever an '@attributes' array occurs, how can I move all the nodes of the '@attributes' array into its parent array, whilst unsetting the '@attributes' array?
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
)
)
)
There is a similar post here (php move nodes to parent array), but the solution provided by @prodigitalson does not work with the multi-dimensional array above.
Edit: The array is an excerpt from the XML response of an API. I am extracting the relevant content with the below code
$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>';
}
}
However, this doesn't do anything to the array (even though it works in the original post) and I didn't get it running for the past hours.