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 Background
s, 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]');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…