-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.php
More file actions
88 lines (77 loc) · 2.67 KB
/
Sort.php
File metadata and controls
88 lines (77 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
class Sort {
/**
* Sort an Array of objects by date
* @var $array = Array to sort
* @var $key = Key in array or object to date value
* @var $direction = ASC or DESC (DESC by default)
* @var $aftertoday = (optionnal) boolean, if true return values only after date of today
* @return array
*/
public function sortByDate(array $array, $key, $direction = "DESC", $aftertoday = false)
{
$type = 'array';
foreach($array as $o){
if(gettype($o) === "object")
$type = 'object';
}
if($aftertoday){
$array = $this->removeAfterToday($array, $type);
}
$result = $this->uSort($array, $type, $key, $direction);
return $result;
}
protected function uSort(array $array, $type, $key, $direction)
{
if($type === 'object'){
if(strtoupper($direction) === 'ASC'){
usort($array, function($a1, $a2) use($key){
return strtotime($a2->{$key}) - strtotime($a1->{$key});
});
} else {
usort($array, function($a1, $a2) use($key){
return strtotime($a1->{$key}) - strtotime($a2->{$key});
});
}
} else {
if(strtoupper($direction) === 'ASC'){
usort($array, function($a1, $a2) use($key){;
return strtotime($a2[$key]) - strtotime($a1[$key]);
});
} else {
usort($array, function($a1, $a2) use($key){
return strtotime($a1[$key]) - strtotime($a2[$key]);
});
}
}
return $array;
}
protected function removeAfterToday($array, $type)
{
$today = strtotime(date('Y-m-d'));
foreach($array as $k => $o)
{
if($type === 'object'){
// First we check if it's a date type
if (false === strtotime($o->{$key})) {
$dateTime = new DateTime($o->{$key});
$date = $dateTime->format('Y-m-d');
$o->{$key} = $date;
}
if(strtotime($o->{$key}) - $today < 0){
unset($array[$k]);
}
} else {
if (false === strtotime($o[$key])) {
$dateTime = new DateTime($o[$key]);
$date = $dateTime->format('Y-m-d');
$o[$key] = $date;
}
if(strtotime($o[$key]) - $today < 0){
unset($array[$k]);
}
}
}
return $array;
}
}