1

I have problem sorting dates in an array.

$data[0]["Venue"];
$data[0]["VenueConfigurationID"];
$data[0]["VenueID"];
$data[0]["TimeStamp"];

$data[2]["Venue"];
$data[2]["VenueConfigurationID"];
$data[2]["VenueID"];
$data[2]["TimeStamp"];

$data[3]["Venue"];
$data[3]["VenueConfigurationID"];
$data[3]["VenueID"];
$data[3]["TimeStamp"];

I want to sort these arrays based on the TimeStamp value.

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
Charlie
  • 21
  • 1

5 Answers5

2

You can use the solution I presented for another question (see the code for the make_comparer function):

usort($data, make_comparer('TimeStamp'));

This will let you sort the data by any number of criteria, and you can easily change the criteria by simply changing the order or the value of the array items.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
0

Probably you are looking for usort. Using this function, you can specify a comparison function that shall be used to compare two elements. Thus, you could write

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

and afterwards:

usort($data, "cmp");
phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • I have tried it.
    '' function cmp($a, $b) { global $array; if($array[$a]['TimeStamp'] < $array[$b]['TimeStamp']){ return false; }else{ return true; } }''
    – Charlie Apr 11 '11 at 12:11
  • @Charlie: Why the `global $array`? `$a` and `$b` are elements directly from your array. Moreover: Why returning `true` or `false`? – phimuemue Apr 11 '11 at 12:14
  • file:///C:/Documents%20and%20Settings/fani/Desktop/C2%20Help/Sample.html – Charlie Apr 16 '11 at 10:32
0

I think you can do this:

function cmp($a, $b){
$a_t = strtotime( $a['TimeStamp'] ) ; 
$b_t = strtotime( $b['TimeStamp'] ) ; 

if ($a_t == $b_t) {
    return 0;
}
return ($a_t < $b_t) ? -1 : 1;
}

usort($data,'cmp');

hope it works

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0

There are a lot of correct answers here, but I usually prefer to use usort with anonymous functions:

PHP ≥ 5.3

usort($data, function($a, $b) {
    return $a['timestamp'] - $b['timestamp'];
});

PHP ≥ 4.0.1

usort($data, create_function('$a, $b',
    'return $a["timestamp"] - $b["timestamp"];'
));
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
0

Use array_multisort function:-

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $timestamp[$key]  = $row['TimeStamp'];        
}

// Sort the data with timestamp descending    
array_multisort($timestamp, SORT_DESC, $data);
?>

Hope this helps.

Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120