[英]Sorting arrays within an array in PHP by datetime
我目前在 PHP 中遇到問題,我想按創建日期對這些帖子進行排序,以便它們可以按降序顯示。 我一直在尋找一個 PHP function 來做到這一點,但沒有運氣。
有一個簡單的解決方案嗎? 任何想法將不勝感激:)
array
0 =>
array
'post_id' => string '1' (length=1)
'user_id' => string '3' (length=1)
'post' => string 'this is a post' (length=14)
'created' => string '2012-04-05 20:11:38' (length=19)
1 =>
array
'post_id' => string '2' (length=1)
'user_id' => string '2' (length=1)
'post' => string 'this is a post' (length=14)
'created' => string '2012-04-05 20:11:38' (length=19)
2 =>
array
'post_id' => string '3' (length=1)
'user_id' => string '5' (length=1)
'post' => string 'this is a post' (length=14)
'created' => string '2012-04-05 20:11:38' (length=19)
試試這個:
<?php
$a=array(
0 =>
array(
'post_id' => '1',
'user_id' => '3',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:40'
),
1 =>
array(
'post_id' => '2',
'user_id' => '2',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:39'
),
2 =>
array(
'post_id' => '3',
'user_id' => '5',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:38'
)
);
function cmp($a,$b){
return strtotime($a['created'])<strtotime($b['created'])?1:-1;
};
uasort($a,'cmp');
print_r($a);
?>
按指定的 mysql 日期時間字段和順序對記錄數組/assoc_arrays 進行排序:
function build_sorter($key, $dir='ASC') {
return function ($a, $b) use ($key, $dir) {
$t1=strtotime(is_array($a)?$a[$key]:$a->$key);
$t2=strtotime(is_array($b)?$b[$key]:$b->$key);
if($t1==$t2) return 0;
return (str_to_upper($dir)=='ASC'?($t1 < $t2):($t1 > $t2)) ? -1 : 1;
};
}
// $sort - key or property name
// $dir - ASC/DESC sort order or empty
usort($arr, build_sorter($sort, $dir));
您可以使用strtotime()
將時間戳轉換為 integer。
您可以使用自定義排序 function 對數組進行排序,如下所示:
function cmp($a, $b) {
if($a['created'] < $b['created']) {
return 1;
} else if ($a['created'] > $b['created']) {
return -1;
} else {
// The only option left is that they are equal
return 0;
}
}
usort($array, cmp);
有關 usort 的更多信息,請查看php 聯機幫助頁
您可以使用usort() function,它允許您根據自己的標准對數組進行排序。
function cmp($a, $b)
{
if ($a['created'] == $b['created']) {
return 0;
}
return ($a['created'] < $b['created']) ? 1 : -1;
}
usort($myArray, "cmp");
print_r($myArray);
或者如果你想轉換為時間:
function cmp($a, $b)
{
if ($a['created'] == $b['created']) {
return 0;
}
$aInt = strtotime($a['created']);
$bInt = strtotime($b['created']);
return ($aInt < $bInt) ? 1 : -1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.