Order Multidimensional Arrays PHP
I have some problem to order an array by a field of this, here i leave the example
foreach($xml as $site){
echo '<d开发者_StackOverflow社区iv><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
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.
<?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); });
精彩评论