Php 是否有一种按月份和年份对数组进行排序的简单方法?
我有一个数组,但我需要按顺序排序。有什么简单的方法可以做到这一点吗?该数组如下所示:Php 是否有一种按月份和年份对数组进行排序的简单方法?,php,arrays,date,sorting,Php,Arrays,Date,Sorting,我有一个数组,但我需要按顺序排序。有什么简单的方法可以做到这一点吗?该数组如下所示: ( [01/2012] => 0 [01/2013] => 4 [02/2011] => 0 [02/2012] => 0 [03/2011] => 0 [03/2012] => 0 [04/2011] => 0 [04/2012] => 0 [05/2011] => 0 [05/2012] => 0 [06/2011] => 0 [06/201
( [01/2012] => 0 [01/2013] => 4 [02/2011] => 0 [02/2012] => 0
[03/2011] => 0 [03/2012] => 0 [04/2011] => 0 [04/2012] => 0
[05/2011] => 0 [05/2012] => 0 [06/2011] => 0 [06/2012] => 0
[07/2011] => 0 [07/2012] => 0 [08/2011] => 0 [08/2012] => 1
[09/2011] => 0 [09/2012] => 5 [10/2011] => 0 [10/2012] => 3
[11/2011] => 0 [11/2012] => 7 [12/2011] => 0 [12/2012] => 2 )
我需要它从最远的地方返回到最新的地方。您可以使用该功能
uksort ( $myArray , function($keyA, $keyB){
$monthYearA = explode('/', $keyA);
$monthYearB = explode('/', $keyB);
return $monthYearA[1].$monthYearA[0] >
$monthYearB[1].$monthYearB[0] ? 1 : -1;
});
解决方法是将每个键转换为unix时间戳,对键进行排序(ksort),然后再将它们转换为月份和年份
while($row = mysql_fetch_array($conversions_query)){
if($row['data']){
$data = unserialize($row['data']);
foreach($data as $month=>$visits){
if($visits == ""){
$visits = 0;
}
$monthstring = explode("/", $month);
$output[strtotime($monthstring[0]."/01/".$monthstring[1])] = $visits;
}
}
}
ksort($output);
foreach($output as $key => $val){
$thisdate = date("m/y", $key)."<br>";
$output[$thisdate] = $output[$key];
unset($output[$key]);
}
echo "<br>SORTED OUTPUT: ";
print_r($output);
while($row=mysql\u fetch\u数组($conversions\u query)){
如果($row['data'])){
$data=unserialize($row['data']);
foreach($月数据=>$访问次数){
如果($visions==“”){
$visions=0;
}
$monthstring=爆炸(“/”,$month);
$output[strottime($monthstring[0])。“/01/”$monthstring[1])]=$visions;
}
}
}
k港口(产出);
foreach($key=>$val的输出){
$thisdate=日期(“m/y”,$key)。“
”;
$output[$thisdate]=$output[$key];
未设置($output[$key]);
}
echo“
排序输出:”;
打印(输出);
您可以构建不同的键吗?ie[201201]=>0为什么不使用unix时间?不幸的是,我使用的是现有应用程序中的阵列,这就是我必须使用的。Ed Heal,你能把一个MM/YYYY转换成一个Unix时间戳,然后按它排序,然后再把它转换回MM/YYYY吗?你可以不写mktime
,只写$arrayA[1]。$arrayA[0]<$arrayB[1]。$arrayB[0]
。我不知道它是否更快:)谢谢你的回答,但我最终还是用Ed Heal的评论解决了这个问题,我将每个键转换为unix时间戳,按键排序(ksort),然后重新转换键,你更喜欢这个解决方案吗?不,在你发布答案时,我已经完成了。