views:

37

answers:

2

Hi everyone

I have some problem to order an array by a field of this, here i leave the example

foreach($xml as $site){
echo '<div><a href="'.$site->loc.'">'.$site->loc.'</a>' .$site->padre.'</div>';
}

Some times the filed $site->padre is empty but i'd like to order by $site->padre alphabetical i saw example with usort but i don't understand how to work it.

Thanks in advance.

Cheers

+3  A: 
function cmp($a, $b){
    return strcmp($a['padre'], $b['padre']);
}

usort($xml, "cmp");
foreach($xml as $site){
    echo '<div><a href="'.$site->loc.'">'.$site->loc.'</a>' .$site->padre.'</div>';
}

The cmp function will be called for every element in the array. The function must return an integer to determine if $a is more, less or equal to $b. Specifying ['padre'] in the cmp function will compare that element.

abrereton
If you wish to maintain the index association in your $xml array, then use uasort instead of usort.
abrereton
+1  A: 
<?php

   function alphabetize($a, $b){
     # property notation as used in original question
     return strcmp($a->padre, $b->padre);
   }

   $xml = uasort($xml, 'alphabetize');
   foreach($xml as $site){
     # your code here
   }

?>

Alternatively, you can use a lambda function using PHP's create_function()

$xml = uasort($xml, create_function('$a,$b', 'return strcmp($a->padre, $b->padre);'));

Or, if you have PHP >= 5.3

$xml = uasort($xml, function($a,$b){ return strcmp($a->padre, $b->padre); });
macek