Sort XML Data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Sort XML Data

Post 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.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Sort XML Data

Post 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
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: Sort XML Data

Post by SidewinderX »

It does indeed do exactly what I want. Thank you very much.
Post Reply