1

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 ) 

)

4

2 回答 2

9

您可能可以使用usort()str系列函数在或上对其进行排序pos。您必须为此定义自己的比较函数。

伪 PHP 示例:

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

uasort($yourArray, "compareItems");

根据您的需要,其他比较功能可能更合适。

于 2010-01-27T12:27:17.410 回答
-1

试试这个功能

function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}
于 2010-01-27T12:25:51.273 回答