如果数组是多维的,如何按第一个值对数组排序? [英] How to sort array by first value if array is multidimensional?
本文介绍了如果数组是多维的,如何按第一个值对数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码创建一个多维数组,其中日期和id是对对象:
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;
然后,我需要运行类似以下内容以按日期排序,然后才能找到也按日期后的ID排序
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);
这是print_r,日期没有排序,id也没有排序
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 ) )
推荐答案
只需更改您的 custom_sort_dt
函数以查看子键:
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']);
}
这篇关于如果数组是多维的,如何按第一个值对数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文