Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

php - Sorting XML with SimpleXML/XPath?

I have some XML, say:

<Backgrounds>
  <Background>
    <Uses>14</Uses>
  </Background>
  <Background>
    <Uses>19</Uses>
  </Background>
  <Background>
    <Uses>3</Uses>
  </Background>
</Backgrounds>

How can I sort the XML from lowest Uses to highest?

Maybe an xpath expression?

Also, how could I just retrieve the bottom 2 Backgrounds, or the ones most recently added?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Examples of sorting with SimpleXML/XPath

How can I sort the XML from lowest Uses to highest?

To sort a list of elements from lowest to highest, you need to create an array of those elements and then sort that array. The xpath expression can be used to obtain both, the array of elements to be sorted as well as the data that array is sorted on (sort-key).

With your XML and the Uses children as sort-value, it works the like the following:

$elements = $xml->xpath('/*/Background');
$sortKeys = $xml->xpath('/*/Background/Uses');

array_multisort($sortKeys, SORT_NUMERIC, SORT_ASC, $elements);

foreach($elements as $i => $element) {
    echo $i, ' ', $element->asXML(), "
";
}

Which results in:

0 <Background>
    <Uses>14</Uses>
  </Background>
1 <Background>
    <Uses>19</Uses>
  </Background>
2 <Background>
    <Uses>3</Uses>
  </Background>

See array_multisort() and "How do I sort a multidimensional array in php".


Also, how could I just retrieve the bottom 2 Backgrounds, or the ones most recently added?

This is possible to do with xpath alone:

$bottomTwo = $xml->xpath('/*/Background[position() > count(/*/Background) - 2]');

And if most recently added mean the ones on top and not on the bottom:

$topTwo = $xml->xpath('/*/Background[position() < 3]');  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...