连续循环遍历PHP数组(或对象键)

时间:2012-10-16 00:01:47

标签: php arrays object foreach continuous

我有一系列对象键:

            $this->rules->days->mon = isset($this->recurring_event_data['post_ar'][$this->rules->type]['mon']) ? true : false;
            $this->rules->days->tue = isset($this->recurring_event_data['post_ar'][$this->rules->type]['tue']) ? true : false;
            $this->rules->days->wed = isset($this->recurring_event_data['post_ar'][$this->rules->type]['wed']) ? true : false;
            $this->rules->days->thu = isset($this->recurring_event_data['post_ar'][$this->rules->type]['thu']) ? true : false;
            $this->rules->days->fri = isset($this->recurring_event_data['post_ar'][$this->rules->type]['fri']) ? true : false;
            $this->rules->days->sat = isset($this->recurring_event_data['post_ar'][$this->rules->type]['sat']) ? true : false;
            $this->rules->days->sun = isset($this->recurring_event_data['post_ar'][$this->rules->type]['sun']) ? true : false;

我有这个功能:

function calc_next_weekly_interval($ii,$i)
{
         global $array;
    // we will roll through this->rules->mon,tue,wed,thu,fri,sat,sun. If its true, return the new iii value, if not keep looping through the array until we hit true again.
    $cur_day = strtolower(date('D',$ii));

    $found_today = false;

    // our initial start date
    $iii = $ii;             

    foreach($this->rules->days as $day => $value)
    {
        if($found_today == true && $value = true)
        {
            return $iii
        }
                    // need to find the current day first!
        if($day == $cur_day)
        {
            $found_today = true;
        }

        $iii + SECS_PER_DAY;            
    }
}
一切都很好。注意我正试图找到当天的下一个真实日期。问题是当我使用星期日作为初始cur_day进行搜索时,显然foreach循环将在找到真正的匹配之前停止。如何连续循环遍历数组(或对象键)?我应该将循环放在一个新函数中并继续使用新的开始日期调用它吗?我不想添加额外的数组键 - >值,因为它会影响以后的事情,我想过只在这个函数中添加初始数组(这里的例子,数组编码用于参考,但在我的class - 它当然是obj keys-> values

2 个答案:

答案 0 :(得分:3)

如果您想连续循环,可以使用

$infinate = new InfiniteIterator(new ArrayIterator($array));
foreach ( $infinate as $value ) {

    // Do your thing
    // Remember to break

}

答案 1 :(得分:1)

怎么样

foreach($this->rules->days as $day => $value)
{ 
    if($day == $cur_day)
    {
        $set = true;
    }

    $iii + SECS_PER_DAY;

    if($found_today == true && $value = true)
    {
        return $iii
    }
                // need to find the current day first!


}