我正在为计算机服务器开发一个简单的调度程序,需要使用这个数组:
Array
(
[Mon] => false,
[Tues] => true,
[Wed] => false,
[Thurs] => true,
[Fri] => true,
[Sat] => true,
[Sun] => false
)
得到一个像这样返回的数组:
Array
(
'Thurs', 'Fri', 'Sat'
)
基本上,我正在寻找阵列连续两次True
的实例。可能是周一,周二,周三,可能是周五,周六,周日,但不一定是周一,周三,周四。
我的第一个想法是想出各种可能性和硬编码作为一个数组,然后foreach
通过每种可能性,但它花了太长时间,并感到草率。
由于
答案 0 :(得分:2)
这将返回第一个3的序列,如果不存在这样的序列则返回一个空数组:
function getDays(array $schedule) {
$sequence = array();
foreach($schedule as $day => $value) {
if($value) {
$sequence[] = $day;
// check if we have enough trues to exit
if(count($sequence) > 2) {
break;
}
}
else {
// we found a false, so reset any existing sequence
$sequence = array();
}
}
return $sequence;
}
$schedule = array(
'Mon' => false,
'Tues' => true,
'Wed' => false,
'Thurs' => true,
'Fri' => true,
'Sat' => true,
'Sun' => false
);
print_r(getDays($schedule));
输出:
Array
(
[0] => Thurs
[1] => Fri
[2] => Sat
)
答案 1 :(得分:0)
<?php
$daysTest = array(
'0-Thurs,Fri,Sat' => array('Mon' => false, 'Tues' => true,'Wed' => false, 'Thurs' => true,'Fri' => true, 'Sat' => true,'Sun' => false)
,'1-Thurs,Fri,Sat' => array('Mon' => true, 'Tues' => true,'Wed' => false, 'Thurs' => true,'Fri' => true, 'Sat' => true,'Sun' => false)
,'2-Mon,Tues,Wed,Thurs,Fri,Sat,Sun' => array('Mon' => true, 'Tues' => true,'Wed' => true, 'Thurs' => true,'Fri' => true, 'Sat' => true,'Sun' => false)
,'3-' => array('Mon' => false, 'Tues' => true,'Wed' => false, 'Thurs' => true,'Fri' => false, 'Sat' => true,'Sun' => true)
);
$minLength = 3;
foreach ($daysTest as $target => $days) {
$result = array();
$stack = array();
foreach ($days as $key => $match) {
if ( $match ) {
$stack[] = $key;
}
else {
if ( $minLength <= count($stack)) {
$result += $stack;
}
$stack = array();
}
}
if ( $minLength <= count($stack)) {
$result += $stack;
}
echo 'Result:',implode(',',$result),"\n";
echo 'Target:',$target,"\n";
}
答案 2 :(得分:0)
以下内容适用于任何天数
$days = array('Mon' => 'false', 'Tues' => 'true',
'Wed' => 'false', 'Thurs' => 'true',
'Fri' => 'true', 'Sat' => 'true',
'Sun' => 'false');
while ($day = array_shift($days)) {
if($day == next($days)) {
$result[] = array_search($day, $days)."<br/>";
}
}
print_r($result);
结果:
Array
(
[0] => Wed
[1] => Thurs
[2] => Fri
)