排序PHP数组但其中的对象

时间:2011-05-10 18:07:56

标签: php

很抱歉,如果这很简单,我是一个PHP新手。

使用基于REST的API我从我正在访问的系统中获得以下结果:

$results = Array ( 
    [0] => stdClass Object ( 
        [ID] => 4d74fcda000291fe949dce44b892c57a   
        [name] => File Quarterly Taxes 
        [objCode] => TASK 
        [status] => NEW 
        [plannedCompletionDate] => 2011-09-09T07:30:00:000-0600 
        [description] => 

        [project] => stdClass Object ( 
            [ID] => 4d3d9cb00000829953755920c930f68a
            [name] => 2010 Accounting 
            [objCode] => PROJ
        )
    )
    [1] => stdClass Object ( 
        [ID] => 4d74fcda000291fd43a0b7c9c8224d3a 
        [name] => File Quarterly Taxes 
        [objCode] => TASK 
        [status] => NEW 
        [plannedCompletionDate] => 2011-06-10T07:30:00:000-0600 
        [description] => 

        [project] => stdClass Object (
            [ID] => 4d3d9cb00000829953755920c930f68a 
            [name] => 2010 Accounting 
            [objCode] => PROJ
        )
    ) 
    [2] => stdClass Object ( 
        [ID] => 4d74fcda000291ffd91d63e25945d2be 
        [name] => File Quarterly Taxes 
        [objCode] => TASK 
        [status] => NEW 
        [plannedCompletionDate] => 2012-01-13T07:30:00:000-0700 
        [description] => 

        [project] => stdClass Object ( 
            [ID] => 4d3d9cb00000829953755920c930f68a 
            [name] => 2010 Accounting 
            [objCode] => PROJ
        )
    )
) 

如何获取该数组并按对象中的plannedCompletionDate对其进行排序?

2 个答案:

答案 0 :(得分:2)

编写一个自定义函数,用于比较2个对象并将其用作usort的回调函数 http://php.net/manual/en/function.usort.php

答案 1 :(得分:2)

function sort_callback( $a, $b ) {
    if( $a->plannedCompletionDate == $b->plannedCompletionDate ) {
        return 0;
    }
    return ( $a->plannedCompletionDate > $b->plannedCompletionDate ) ? 1 : -1;
}

usort( $results, 'sort_callback' );