簡體   English   中英

如何對數組中的最新日期排序?

[英]How can i sort after the newest date in my array?

如何對數組中的最新日期排序?

這是我的數組($ testarray)的輸出:

Array ( 
[0] => Array ( [created] => 16-02-13 20:41:56 [restaurant_id] => 64324 [title] => Café Blabla [city] => State K ) 
[1] => Array ( [created] => 19-02-13 13:42:14 [restaurant_id] => 42132 [title] => Chicos Blabla [city] => State K ) 
[2] => Array ( [created] => 17-02-13 19:41:30 [restaurant_id] => 51242 [title] => Restaurant Blabla  [city] => State K ) 
[3] => Array ( [created] => 18-02-13 16:42:12 [restaurant_id] => 64342 [title] => Couloir Blabla [city] => State S )

嘗試這個 :

<?php

$arr=your array;


$sort = array();
foreach($arr as $k=>$v) {
    $sort['created'][$k] = $v['created'];

}

array_multisort($sort['created'], SORT_DESC, $arr);

echo "<pre>";
print_r($arr);

?>

您可以使用asort()ksort()對數組進行排序。

你可以在這里學習

http://php.net/manual/en/array.sorting.php

usort允許您通過提供函數回調來基於自定義方法進行排序:

// Sorts two array elements based on the value of the
// `[created]` element.
function SortByDateCreatedDate($x,$y){
  $xd = $x['created']; //or if they're strings:*/ strtotime($x['created']);
  $yd = $y['created']; //or if they're strings:*/ strtotime($y['created']);
  return $xd > $yd ? 1
    : $yd > $xd ? -1
    : 0;
}

$testarray = /*...*/;
usort($testarray, 'SortByCreatedDate');
<?php

$dts = array_map(function($x) { $x['created']; }, $array);
$max = max($dts);
$idx = array_search($max, $dts);
$do_not_sort = array_slice($array, 0, $idx);
$do_sort = array_slice($array, $idx);

function cmp($x, $y) {
    $a = $x['created'];
    $b = $y['created'];
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

uasort($do_sort, 'cmp');
$sorted[] = $do_not_sort;
$sorted[] = $do_sort;

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM