How to sort array by first value if array is multidimensional?

半城伤御伤魂 提交于 2020-01-06 07:36:07

问题


The following creates a multidimensional array, where a date and id are pair objects:

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

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

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

回答1:


Just change your custom_sort_dt function to look at the sub keys:

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


来源:https://stackoverflow.com/questions/53697794/how-to-sort-array-by-first-value-if-array-is-multidimensional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!