Home  >  Article  >  Backend Development  >  Problem sorting by key in array?

Problem sorting by key in array?

WBOY
WBOYOriginal
2016-12-01 00:56:301154browse

<code>$test=array(60) {
 [0]=> object(stdClass)#14 (3) { ["id"]=> string(3) "609" ["title"]=> string(19) "Physical Mechanisms" ["publish_time"]=> string(10) "6 MAY 2016" }
 [1]=> object(stdClass)#14 (3) { ["id"]=> string(3) "610" ["title"]=> string(20) "Engineering Substrate" ["publish_time"]=> string(10) "2 MAY 2016" }
  ...}
 

</code>

How to sort $test according to publish_time? consult!

Reply content:

<code>$test=array(60) {
 [0]=> object(stdClass)#14 (3) { ["id"]=> string(3) "609" ["title"]=> string(19) "Physical Mechanisms" ["publish_time"]=> string(10) "6 MAY 2016" }
 [1]=> object(stdClass)#14 (3) { ["id"]=> string(3) "610" ["title"]=> string(20) "Engineering Substrate" ["publish_time"]=> string(10) "2 MAY 2016" }
  ...}
 

</code>

How to sort $test according to publish_time? consult!

You can use the php function usort to customize the sorting

<code><?php
function _usort($a, $b) {
    if ( strtotime($a->publish_time) < strtotime($a->publish_time) ) {
        return -1;
    } else if( strtotime($a->publish_time) > strtotime($a->publish_time) ){
        return 1;
    } else {
        return 0;
    }
}

usort($arr, '_usort');</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn