2013-02-20 60 views
0

我如何排序我的數組中的最新日期?我如何排序我陣列中的最新日期?

這是我的數組(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) 
+1

看一看['usort'] (http://www.php.net/usort) – 2013-02-20 13:29:48

+0

按什麼排序? – 2013-02-20 13:31:12

+0

我的數組中的Neweste日期^^^^^^^^ – Zaz 2013-02-20 13:42:36

回答

0

試試這個:

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

?> 
0

您可以使用asort()ksort()排序的陣列。

,你可以在這裏學習它

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

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'); 
0
<?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; 

?>