0

我有一个这样的 simplexml 对象

<aaaa>
    <bbbb>0000</bbbb>
    <cccc>0000</cccc>
    <dddd>
        <eeee>
          <gggg>1111</gggg>
          <hhhh>2222</hhhh>
          <mmmm>3333</mmmm>
        </eeee>
        <eeee>
          <gggg>4444</gggg>
          <hhhh>5555</hhhh>
          <mmmm>6666</mmmm>
        </eeee>
        <eeee>
          <gggg>7777</gggg>
          <hhhh>8888</hhhh>
          <mmmm>9999</mmmm>
        </eeee>
    </dddd>
</aaaa>

我怎样才能获得如下的新结构?(新元素 ffff 包含以相反顺序排列的 dddd 的相同子级列表)

<aaaa>
    <bbbb>0000</bbbb>
    <cccc>0000</cccc>
    <dddd>
        <eeee>
          <gggg>1111</gggg>
          <hhhh>2222</hhhh>
          <mmmm>3333</mmmm>
        </eeee>
        <eeee>
          <gggg>4444</gggg>
          <hhhh>5555</hhhh>
          <mmmm>6666</mmmm>
        </eeee>
        <eeee>
          <gggg>7777</gggg>
          <hhhh>8888</hhhh>
          <mmmm>9999</mmmm>
        </eeee>
    </dddd>
    <ffff>
        <eeee>
          <gggg>7777</gggg>
          <hhhh>8888</hhhh>
          <mmmm>9999</mmmm>
        </eeee>
        <eeee>
          <gggg>4444</gggg>
          <hhhh>5555</hhhh>
          <mmmm>6666</mmmm>
        </eeee>
        <eeee>
          <gggg>1111</gggg>
          <hhhh>2222</hhhh>
          <mmmm>3333</mmmm>
        </eeee>
    </ffff>
</aaaa>

我试图迭代 dddd 的子级并将它们插入到要使用 array_reverse 反转的对象数组中......但是当我尝试将对象插入回主结构中时,结果被破坏/不完整

4

1 回答 1

1

您可以遍历这些子元素并将它们<ffff>以正确的顺序插入到新元素中。

这很容易通过将您现有的SimpleXMLElement使用与DOM 扩展提供的额外功能混合在一起来完成。不需要中间数组或对它们进行排序。

$aaaa = simplexml_load_string($xml_string);

// Add new <ffff> element
$ffff = $aaaa->addChild('ffff');

// Get DOMElement instance for <ffff>
$ffff_dom = dom_import_simplexml($ffff);

// Loop over <dddd> children and prepend to <ffff>
foreach ($aaaa->dddd->children() as $child) {
    $child_copy = dom_import_simplexml($child)->cloneNode(TRUE);
    $ffff_dom->insertBefore($child_copy, $ffff_dom->firstChild);
}

// Go back to SimpleXML-land and see the result
echo $aaaa->saveXML();

见这个在线运行的例子。

于 2012-11-18T23:27:41.623 回答