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

时间:2014-07-05 18:37:28

标签: php arrays

您好我正在尝试使用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 :(得分:0)

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

答案 1 :(得分: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];
}