Page 1 of 1

Sort XML Data

Posted: Thu Jan 24, 2008 8:12 pm
by SidewinderX
I've been playing around with SimpleXMLElement to parse XML document, and I've been trying to sort the data by one if its elements. My code does just that, but I was wondering if is a efficient / elegant implementation.

Code: Select all

<?php
$xml = new SimpleXMLElement($xmlstr); 
 
$i = 0;
foreach ($xml->PLAYERLIST->PLAYER as $player) {
    $var[$i] = (int)$player->PLAYERKILLS;
    $i++;
}  
 
sort($var);
$i = 0;
foreach ($var as $key => $val) {
    $sorted[$i] = $val;
    $i++;
}

print_r(array_reverse($sorted));
 
?>
Thanks.

Re: Sort XML Data

Posted: Fri Jan 25, 2008 4:21 am
by s.dot
sort() will sort the array. You don't need to loop through it again assigning to the $sorted array. I think instead of sort() you should be using rsort(). It will save you the array_reverse() call. Also, I don't believe you need to enumerate your keys. So unless i'm reading it wrong because I'm tired, you could have:

Code: Select all

<?php
$xml = new SimpleXMLElement($xmlstr);
 
$var = array();
foreach ($xml->PLAYERLIST->PLAYER as $player) {
    $var[] = (int) $player->PLAYERKILLS;
}  
 
rsort($var, SORT_NUMERIC);
print_r($var) //should be the same as what you have now

Re: Sort XML Data

Posted: Sat Jan 26, 2008 12:00 pm
by SidewinderX
It does indeed do exactly what I want. Thank you very much.