简体   繁体   English

如果数组是多维的,如何按第一个值对数组排序?

[英]How to sort array by first value if array is multidimensional?

The following creates a multidimensional array, where a date and id are pair objects: 下面创建一个多维数组,其中日期和id是对对象:

if( $queryPosts->have_posts() ):
    $dateOrdered = [];
    while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
        $id = $post->ID;
        $date = usp_get_meta(false, 'usp-custom-80');
        array_push($postOrdered, $id);
        $dateOrdered[] = array("date"=>$date, "id"=>$id);
    endwhile;
endif;

Then I need to run something like the following to sort by dates in order to then have a list of ordered by dates post ids too 然后我需要运行类似以下内容以按日期排序,以便然后获得按日期排序的列表,也包含ID

function custom_sort_dt($a, $b) {
    return strtotime($a) - strtotime($b);
}
usort($dateOrdered, "custom_sort_dt");
print_r($dateOrdered);  

This is the print_r and dates are not ordered and so are not the ids 这是print_r,日期没有排序,所以id也没有排序

Array ( [0] => Array ( [date] => 7-12-2018 [id] => 127902 ) [1] => Array ( [date] => 19-12-2018 [id] => 127982 ) [2] => Array ( [date] => 6-12-2018 [id] => 127987 ) [3] => Array ( [date] => 13-12-2018 [id] => 127899 ) [4] => Array ( [date] => 24-11-2000 [id] => 127891 ) [5] => Array ( [date] => 13-11-2018 [id] => 127867 ) [6] => Array ( [date] => 25-11-2018 [id] => 127869 ) [7] => Array ( [date] => 5-12-2018 [id] => 127990 ) [8] => Array ( [date] => 5-12-2018 [id] => 127992 ) [9] => Array ( [date] => 18-12-2018 [id] => 128009 ) [10] => Array ( [date] => 26-12-2018 [id] => 128011 ) [11] => Array ( [date] => 21-12-2018 [id] => 128015 ) [12] => Array ( [date] => 27-12-2018 [id] => 128005 ) [13] => Array ( [date] => 12-11-2018 [id] => 127999 ) [14] => Array ( [date] => 7-12-2018 [id] => 127994 ) [15] => Array ( [date] => 21-12-2018 [id] => 127996 ) [16] => Array ( [date] => 2-6-2015 [id] => 128019 ) )

Just change your custom_sort_dt function to look at the sub keys: 只需更改您的custom_sort_dt函数以查看子键:

function custom_sort_dt($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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