PHP : Loops, arrays and sorting
public function getAl开发者_开发技巧lEventsByDate($allEvents, $date) {
$theEvents = array();
foreach ($allEvents as $event) {
if ($date == 'future' && $event['start'] > time())
$theEvents[] = $event;
else if ($date == 'past' && $event['stop'] < time())
$theEvents[] = $event;
else if ($date == 'current' && $event['start'] < time() &&
$event['stop'] > time())
$theEvents[] = $event;
}
return $theEvents;
}
My boss was surprised that I use every time $theEvents[]
.
How would you do this?
Maybe code should look like this.
public function getAllEventsByDate($allEvents, $date) {
$theEvents = array();
foreach ($allEvents as $event) {
$condition =
($date == 'future' && $event['start'] > time()) ||
($date == 'past' && $event['stop'] < time()) ||
($date == 'current' && $event['start'] < time() &&
$event['stop'] > time())
;
if ($condition) {
$theEvents[] = $event;
}
}
return $theEvents;
}
My boss was surprised that I use every time
$theEvents[]
. How would you do this?
I'd do it... just like that, actually. That code seems relatively simple, straightforward and entirely unambiguous. It's a little verbose (you could condense it into a single if
check), but it's verbose for a purpose and is very clear.
What are your boss' concerns?
Since all of your conditional branches lead to the same statement, it can be written as one if-statement (see below).
public function getAllEventsByDate($allEvents, $date) {
$theEvents = array();
foreach ($allEvents as $event) {
if (
( ($date == 'future') && ($event['start'] > time()) ) ||
( ($date == 'past') && ($event['stop'] < time()) ) ||
( ($date == 'current') && ($event['start'] < time()) && ($event['stop'] > time()) )
) {
$theEvents[] = $event;
}
return $theEvents;
}
Based on the response of Whirlpool :
public function getAllEventsByDate($allEvents, $date) {
$theEvents = array();
$condition1 = ($date == 'future' && $event['start'] > time());
$condition2 = ($date == 'past' && $event['stop'] < time());
$condition3 = ($date == 'current' && $event['start'] < time()
&& $event['stop'] > time());
foreach ($allEvents as $event)
if ($condition1 || $condition2 || $condition3)
$theEvents[] = $event;
return $theEvents;
}
精彩评论