首页 文章

foreach循环中比较元素的未定义偏移量

提问于
浏览
0

嗨,我正在尝试使用foreach循环比较2个元素的日期 . 只要它们匹配,就将它们添加到一个数组中并将该数组推送到另一个数组中 .

这个想法是我将它们全部显示在一个表中,匹配的元素 - 日期将其日期列分组(colspan = n) . 使用辅助数组我将能够使用该数组的长度作为colspan数量 .

$elements = array();
$ts_index = 0;

foreach($timesheetweeks as $timesheetweek){
    $arr = array();
    foreach($timesheetweek->timesheets as $index => $timesheet){

        $this_date = $timesheetweek->timesheets[$index]->start_date;
        $next_date = $timesheetweek->timesheets[$index + 1]->start_date;

        if($this_date == $next_date){
            $elements[$ts_index][] = $timesheetweek->timesheets[$index + 1];
        } else {
            $elements[$ts_index] = $timesheetweek->timesheets[$index];
            $ts_index += 1;
        }
    }
}

不幸的是,在经历了一些令人头疼的事情以及与阿根廷队失利的比赛后,我得到以下错误:

未定义的偏移量:4

fyi:这是我试图实现的目标:

elements [
    1 => element1, //diff date
    2 => array( //same date array
        element2,
        element3
    ),
    3 => element4 //diff date
]

2 回答

  • 0

    不完全确定一些代码,但这个一般的想法应该有所帮助:

    $elements = array();
    $ts_index = -1;
    $currentDate = '';    
    
    foreach ($timesheetweeks as $timesheetweek) {
    
        foreach ($timesheetweek->timesheets as $index => $timesheet) {
    
          if ($timesheet->start_date != $currentDate) {
    
            // check to see if the last $elements element had just one entry, if so flatten it
            if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
              $elements[$ts_index] = $elements[$ts_index][0];
            }
    
            $currentDate = $timesheet->start_date;
            $ts_index++;
    
            // create a new array to store this timesheet and any more that may have the same start_date
            $elements[$ts_index] = array();
          }
    
          $elements[$ts_index][] = $timesheet;
    
        }
    }
    
    // if the last element we added is an array with 1 item, flatten it
    if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
       $elements[$ts_index] = $elements[$ts_index][0];
    }
    
  • 0

    $index 达到其最大值 $index = count($timesheetweek->timesheets) -1; 时,项目 $timesheetweek->timesheets[$index + 1] 不存在 .

相关问题