繁体   English   中英

如何在PHP中的重复子节点上选择和排序XML

[英]How to select and sort XML on repeating child node in PHP

我有一个有关绘画数据的XML文件。 每幅画都可以属于一个或多个画廊。 我需要能够按画廊选择绘画,然后将该列表按位置顺序排序。 因此,例如,我具有以下XML:

<Paintings>
  <Painting>
    <Title>Painting 1</Title>
    <Description>ABC</Description>
    <Galleries>
      <Gallery id="01">1</Gallery>
      <Gallery id="02">3</Gallery>
    </Galleries>
    <Picturefile>painting1</Picturefile>
  </Painting>
  <Painting>
    <Title>Painting 2</Title>
    <Description>DEF</Description>
    <Galleries>
      <Gallery id="02">2</Gallery>
      <Gallery id="03">2</Gallery>
    </Galleries>
    <Picturefile>painting2</Picturefile>
  </Painting>
  <Painting>
    <Title>Painting 3</Title>
    <Description>GHI</Description>
    <Galleries>
      <Gallery id="01">2</Gallery>
      <Gallery id="03">1</Gallery>
    </Galleries>
    <Picturefile>painting3</Picturefile>
  </Painting>
  <Painting>
    <Title>Painting 4</Title>
    <Description>JKL</Description>
    <Galleries>
      <Gallery id="02">1</Gallery>
      <Gallery id="03">3</Gallery>
    </Galleries>
    <Picturefile>painting4</Picturefile>
  </Painting>
</Paintings>

例如,我需要选择画廊“ 02”中的绘画,然后将它们按位置顺序排序。 在上面的xml中,节点值代表该图库的排序顺序。 对于选择,我将使用:

$gallerypics = ($paintings->xpath("Painting/Galleries/Gallery[@id='$galleryid']"));

在这一点上我被卡住了。 然后,如何在该特定图库的节点值上排序$ gallerypics? 我可以选择将排序顺序设置为属性而不是值,但是我仍然对如何对它排序感到困惑。 如果每幅画只有一个Gallery节点,那是不费吹灰之力。 我对如何使用多个Gallery节点执行此操作感到困惑。 任何输入,不胜感激。

基本想法只是选择您想要的绘画,将它们转储到一个数组中,然后根据您的标准对其进行排序


例:

//$xml = your xml string
$galleryid = '02';

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

$paintings = iterator_to_array($xpath->query("/Paintings/Painting[Galleries/Gallery/@id='$galleryid']"));
usort(
    $paintings,
    function ($a, $b) use ($xpath, $galleryid) {
        $query = "number(Galleries/Gallery[@id='$galleryid'])";
        return $xpath->evaluate($query, $a) - $xpath->evaluate($query, $b);
    }
);

foreach ($paintings as $painting) {
    echo $xpath->evaluate('string(Title)', $painting), "\n";
}

输出:

Painting 4
Painting 2
Painting 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM