I've created an array with multiple objects, these objects have a startTime and a endTime. first i need the lowest startTime and then the higest endTime
array{
[1541] => object(task)#430 (2){ ["startTime"]=> string(19) "2016-03-24 06:29:35" ["endTime"]=> string(19) "2016-03-24 06:31:35"}
[1545] => object(task)#431 (2){ ["startTime"]=> string(19) "2016-03-24 07:20:50" ["endTime"]=> string(19) "2016-03-24 07:25:50"}
}
So for this example the lowest startTime would be "2016-03-24 07:25:50" and the highest endTime would be "2016-03-24 07:25:50". But the weird thing is that this isn't (always) the result i'm getting (3 out of 5 times)
the result is lowest startTime is "2016-03-24 07:25:50" and the highest endTime is "2016-03-24 06:29:35"
I order these objects using usort based on the startTime attribute. Here is te code i'm using
class StaticsComponent extends CComponent {
public static function cmp_start($a, $b) {
if (microtime($a->startTime) == microtime($b->startTime)) {
return 0;
}
return (microtime($a->startTime) > microtime($b->startTime)) ? -1 : 1;
}
public static function cmp_end($a, $b) {
if (microtime($a->startTime) == microtime($b->startTime)) {
return 0;
}
return (microtime($a->startTime) < microtime($b->startTime)) ? -1 : 1;
}
}
class OrderBcStats extends Orderbc {
public $tasks;
public $startTime;
public $endTime;
public function process(){
if(empty($this->tasks)){
return;
}
$starts = $this->tasks;
$ends = $this->tasks;
usort($starts, array('StaticsComponent','cmp_start'));
usort($ends, array('StaticsComponent','cmp_end'));
$first = reset($starts);
$last = end($ends);
$this->startTime = $first->startTime;
$this->endTime = $last->endTime;
}
}
additional info: this is a Yii project, PHP Version 5.4.40, OS Centos, apache 2.0
As per the docs "microtime() returns the current Unix timestamp with microseconds" (emphasis added). The only param it takes is a boolean $get_as_float
. So you are not sorting according to the times of the items, but according (roughly) to their order.
You could create DateTime objects and compare their timestamps. however, if you are certain of the format then you could exploit the fact that for ISO format dates, alphabetical order and date order are the same thing...
So I guess instead of
if (microtime($a->startTime) == microtime($b->startTime)) {
return 0;
}
return (microtime($a->startTime) > microtime($b->startTime)) ? -1 : 1;
you want something like
if ($a->startTime == $b->startTime) {
return 0;
}
return ($a->startTime > $b->startTime) ? -1 : 1;
or alternatively
$a_time = new DateTime($a->startTime);
$b_time = new DateTime($a);
if ($a_time == $b_time) {
return 0;
}
return ($a_time > $b_time) ? -1 : 1;
Warning: not tested, but should work.