phparrayslaravel

How to fix Array error Undefined Offset in PHP


Concat the data that have same date but error on 3rd iteration. Concat the data that have same date but error on 3rd iteration.

 $summary = SummaryReport::with('accomplishments.employee')->with(['accomplishments' => function 
 ($query) use ($employee) {
        $query->where('emp_id', $employee->id);
        $query->orderBy('date', 'ASC');
 }])->find($id);

    $accomplishments = [];
    $date = "";

    for ($i = 0; $i < count($summary->accomplishments); $i++) {
        if ($summary->accomplishments[$i]["date"] == $date) {
            $accomplishments[$i - 1]['accomplishment'] = $accomplishments[$i - 1]['accomplishment'] . ', ' . $summary->accomplishments[$i]['accomplishment'];
            continue;
        }
        array_push($accomplishments, $summary->accomplishments[$i]);
        $date = $summary->accomplishments[$i]['date'];
    }

Solution

  • Accomplishments of a particular employee from a particular SummaryReport, grouped by the date

    After your query do the following

    $acc_by_date = $summary->accomplishments->groupBy('date');
    
    $result = [];
    foreach($acc_by_date as $date => $accs){
       $result[$date] = [
           'accomplishments' => $accs->pluck('accomplishment')->reduce(
               function ($carry, $item) {
                  return $carry . ", " .  $item;
           }),
           'remarks' => $accs->pluck('remarks')->reduce(
               function ($carry, $item) {
                  return $carry . ", " .  $item;
           }),
           'remarks_as_array' => $accs->pluck('remarks') 
       ];
    }