简体   繁体   中英

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

I have an XML file of data about paintings. Each painting can belong to one or more galleries. I need to be able to select paintings by gallery, and then sort that list into position order. So, for example, I have XML as follows:

<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>

As an example, I need to select paintings in gallery "02" and then sort them into position order. In the above xml, the node value represnts the sort order for that gallery. For the select, I would use:

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

It's at this point I'm stuck. How do I then sort $gallerypics on the node value for that specific gallery? I have the option of making the sort order an attribute rather than a value, but I'm still stuck on how to sort that. If there was only one Gallery node per painting, this is a no brainer. I'm stuck on how to do this with multiple Gallery nodes. Any input is greatly appreciated.

Basic idea is just to select the paintings you're after, dump them into an array, and sort it based on your criteria.


Example:

//$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";
}

Output:

Painting 4
Painting 2
Painting 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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