我很抱歉要写这么长的帖子,但是我想清楚地说明我的问题。感谢任何帮助。
我有一个名为$data的数组,格式如下:
... ...
给定一个任意的开始日期,我需要搜索数组以查找匹配的日期:
//$holidays is an array with dates of public holidays which are not considered business days
$search_results = array();
$minDate = -10;
$maxDate = 100;
$start_date = "2015-02-25";
echo "Before loop: " . xdebug_time_index() . "<br>";
for ($i=$minDate; $i<=$maxDate; $i++) {
if (in_array_r(getBusinessDay(new DateTime($start_date), $holidays, $i), $data)){
$a_date = getBusinessDay(new DateTime($start_date), $holidays, $i);
$a_key = array_search($a_date, array_column($data, "date"));
$search_results[]=array($i, $data[$a_key]["data"]);
}
}
echo "After loop: " . xdebug_time_index() . "<br>";
var_dump($search_results);
然而,这段代码片段在页面加载时可能会运行10-15次,每次执行需要很长时间(至少在更大的数组上需要6秒钟):
以下是代码片段中使用的函数:
function getBusinessDay($startdate, $holidays, $days) {
$calculator = new BusinessDaysCalculator($startdate, $holidays, [BusinessDaysCalculator::SATURDAY, BusinessDaysCalculator::SUNDAY]);
$calculator->addBusinessDays($days);
$result = $calculator->getDate()->format('Y-m-d');
unset($calculator);
return $result;
}
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
这是一款计算器,它会返回下一个工作日(周末和$holidays数组中的任何日期都会被跳过):
class BusinessDaysCalculator {
const MONDAY = 1;
const TUESDAY = 2;
const WEDNESDAY = 3;
const THURSDAY = 4;
const FRIDAY = 5;
const SATURDAY = 6;
const SUNDAY = 7;
/**
* @param DateTime $startDate Date to start calculations from
* @param DateTime[] $holidays Array of holidays, holidays are no considered business days.
* @param int[] $nonBusinessDays Array of days of the week which are not business days.
*/
public function __construct(DateTime $startDate, array $holidays, array $nonBusinessDays) {
$this->date = $startDate;
$this->holidays = $holidays;
$this->nonBusinessDays = $nonBusinessDays;
}
public function addBusinessDays($howManyDays) {
$i = 0;
while ($i < abs($howManyDays)) {
if ($howManyDays < 0) {
$this->date->modify("-1 day");
} else {
$this->date->modify("+1 day");
}
if ($this->isBusinessDay($this->date)) {
$i++;
}
}
}
public function getDate() {
return $this->date;
}
private function isBusinessDay(DateTime $date) {
if (in_array((int)$date->format('N'), $this->nonBusinessDays)) {
return false; //Date is a nonBusinessDay.
}
foreach ($this->holidays as $day) {
if ($date->format('Y-m-d') == $day->format('Y-m-d')) {
return false; //Date is a holiday.
}
}
return true; //Date is a business day.
}
}
更新 1: 我已经更新了 $data 数组的结构为
循环如下:
for ($i=$minDate; $i <= $maxDate; $i++) {
$day = getBusinessDay(new DateTime($start_date), $holidays, $i);
if (array_key_exists($day, $data)) {
$search_results[]=array($i, $data[$day]);
}
}
时间只有稍微改善:
是array_key_exists导致了延迟吗?
更新2: 这是$holidays数组(它是静态的,总是相同的):
$i++
改为++$i
,这样可以稍微减少时间。 - H Aßdøµ