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

Categories

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

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

1 Answer

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]');  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...