我需要将当前时间与数组中的时间进行比较,并相应地返回相关值。所以我有这样的数组:
$class[0]["start"] = 80000;
$class[0]["end"] = 80500;
$class[0]["title"] = "Warmup";
$class[1]["start"] = 80501;
$class[1]["end"] = 85000;
$class[1]["title"] = "1. class";
$class[2]["start"] = 85001;
$class[2]["end"] = 90000;
$class[2]["title"] = "Break";
我需要将其与当前时间进行比较:
$time = (int) date('Gis');
我可以用这样的硬编码方式:
if($time >= $class[1]["start"] && $time <= $class[1]["end"]) {
$title = $class[1]["title"];
} elseif($time >= $class[2]["start"] && $time <= $class[2]["end"]) {
$title = $class[2]["title"];
etc ...
但我相信有一种更好的方法来返回";标题";没有写几百行elseif。
知道吗?
Thanx
Maros
你可以这样做。。
<?php
$time = (int) date('Gis');
$class[0]["start"] = 80000;
$class[0]["end"] = 80500;
$class[0]["title"] = "Warmup";
$class[1]["start"] = 80501;
$class[1]["end"] = 85000;
$class[1]["title"] = "1. class";
$class[2]["start"] = 85001;
$class[2]["end"] = 90000;
$class[2]["title"] = "Break";
foreach($class as $val){
if($time >= $val["start"] && $time <= $val["end"]) {
$title .= $val["title"];
}
}
echo $title;
?>
扩展El_Vanja的注释,您可以将循环数组和过滤其数据分为两个单独的函数,这样您的代码就变得更加稀疏和可读。
例如,给定您的阵列:
$class = [
[
"start" => 80000,
"end" => 80500,
"title" => "Warmup",
],
[
"start" => 80501,
"end" => 85000,
"title" => "1. class",
],
[
"start" => 85001,
"end" => 90000,
"title" => "Break",
],
];
你可以这样做:
function is_between(int $value, int $low, int $high) {
return ($value >= $low && $value <= $high);
}
function filter(array $data, int $time) {
foreach ($data as $row) {
if (is_between($time, $row['start'], $row['end'])) {
return $row;
}
}
}
简单地称之为:
var_dump(filter($class, 80100));
var_dump(filter($class, 86000));
var_dump(filter($class, 80600));