dongshenling6585 2017-02-02 20:58
浏览 24

PHP将多维数组中的节点移动到父数组

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 fesafe材料库问题
    • ¥35 beats蓝牙耳机怎么查看日志
    • ¥15 Fluent齿轮搅油
    • ¥15 八爪鱼爬数据为什么自己停了
    • ¥15 交替优化波束形成和ris反射角使保密速率最大化
    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统