Sorting arrays by date

后端 未结 3 2112
梦毁少年i
梦毁少年i 2021-01-28 11:36

I\'ve got a question. I\'m building an array by getting data from mysql and merging three query results in one array.

I put data to array like this:

whil         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 12:18

    What you're trying to do is sort a multidimensional array, you can find plenty on Google about this. A nice elegant solution would be something like:

    // Sort the multidimensional array
    usort($results, "custom_sort");
    
    // Define the custom sort function
    function custom_sort($a,$b) {
         return $a['some_sub_var']>$b['some_sub_var'];
    }
    

    EDIT 1:

    For those in the comments doubting whether this code would work, please feel free to try it out (I even added in a date that's a duplicate for testing purposes):

    function custom_sort($a,$b) {
            return $a['added']>$b['added'];
    }
    
    $arrayToSort = array(
                        array(
                            "added" => "2012-01-17 07:33:53",
                            "type" => "1"
                        ),
                        array(
                            "added" => "2012-01-13 06:36:22",
                            "type" => "1"
                        ),
                        array(
                            "added" => "2012-01-09 04:01:12",
                            "type" => "2"
                        ),
                        array(
                            "added" => "2012-02-08 02:08:32",
                            "type" => "2"
                        ),
                        array(
                            "added" => "2012-01-25 00:09:08",
                            "type" => "2"
                        ),
                        array(
                            "added" => "2012-01-13 06:36:22",
                            "type" => "1"
                        ),
                        array(
                            "added" => "2012-01-13 06:36:22",
                            "type" => "1"
                        ),
                        array(
                            "added" => "2012-01-23 00:09:08",
                            "type" => "3"
                        ),
                        array(
                            "added" => "2012-01-22 00:09:08",
                            "type" => "3"
                        )
                    );
    usort($arrayToSort, "custom_sort");
    
    echo '
    ';
    print_r($arrayToSort);
    echo '
    ';

    A good place to test quickly would be to go to http://writecodeonline.com/php/.

提交回复
热议问题