Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do is sort this object by 'pos' in php?

Array ( 
[0] => stdClass Object ( [str] => Mondays [pos] => 170 ) 
[1] => stdClass Object ( [str] => Tuesdays [pos] => 299 )
[2] => stdClass Object ( [str] => Wednesdays [pos] => 355 )
[3] => stdClass Object ( [str] => Thursdays [pos] => 469 )
[4] => stdClass Object ( [str] => Fridays [pos] => 645 )
[5] => stdClass Object ( [str] => Mondays [pos] => 972 )
[6] => stdClass Object ( [str] => Tuesdays [pos] => 1033 ) 
[7] => stdClass Object ( [str] => Thursdays [pos] => 1080 )
[8] => stdClass Object ( [str] => Fridays [pos] => 1180 ) 

)

share|improve this question
4  
What do you want to sort the array by? str? pos? –  Pekka 웃 Jan 27 '10 at 12:23
add comment

2 Answers

up vote 8 down vote accepted

You could probably use the usort() family of functions to sort it either on str or pos. You have to define your own comparison function for that.

Pseudo-PHP example:

function compareItems($a, $b)
{
    if ( $a->pos < $b->pos ) return -1;
    if ( $a->pos > $b->pos ) return 1;
    return 0; // equality
}

uasort($yourArray, "compareItems");

Depending on your needs, other comparison functions might be more appropriate.

share|improve this answer
1  
that worked great - thanks! –  significance Jan 27 '10 at 12:39
add comment

Try this function

function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}
share|improve this answer
    
Perhaps a little bit of explanation would be helpful? –  csl Jan 27 '10 at 12:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.