我如何在PHP中排序以下数组/ stdclass对象?

时间:2010-01-27 12:22:30

标签: php arrays object sorting stdclass

如何在php中用'pos'对这个对象进行排序?

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 ) 

2 个答案:

答案 0 :(得分:9)

您可以使用usort()系列函数对strpos进行排序。你必须为此定义自己的比较函数。

伪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");

根据您的需要,other comparison functions可能更合适。

答案 1 :(得分:-1)

尝试此功能

function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}