简体   繁体   中英

Sort PHP array but the objects within

Sorry if this is simple, I am a PHP newbie.

Using a REST based API I am getting the following results back from the system I am accessing:

$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
        )
    )
) 

How do I take that array and sort it by the plannedCompletionDate in the object?

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

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

usort( $results, 'sort_callback' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM