I have an XML file that has the following data in…
<posts>
<post id="22359">
<postviews>31</postviews>
</post>
<post id="20963">
<postviews>1</postviews>
</post>
<post id="20595">
<postviews>3</postviews>
</post>
<post id="22640">
<postviews>72</postviews>
</post>
<post id="22227">
<postviews>1</postviews>
</post>
...etc etc
</posts>
I’d like to find the top 10 highest postview values and then get the parent node post id so I’d essentially have the id’s of the top 10 postviews.
I have no idea how to go about this, can anyone help? Is the XML file already an array if I load it via…
$xml = simplexml_load_file($xmlFile);
Thanks, James
It can be done by adding each
postSimpleXML element to an array, and then sorting that array usingusort():If you only want the top 10 then just use a
forloop or add a check to stop the loop after the first 10, or you canunset()everything after the first 10.Outputs
Codepad Demo