Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

Fix foreach loop to do what's excepted

This is the code I have right now

if ($item -> response_type_id == 2) {
    $record = 0;
    $recording = collect([]);
    $labels = collect([]);

    foreach($item['surveyQuestionOption'] as $option) {
        $labels[] = $option -> option;
        foreach($answer as $d) {
            if ($option -> id == $d - > answer) {
                $record++;
            }
        }
    }

    $recording[] = $record;
    $record = 0;

    if (count($answer) == $totalAnswered) {
        $itemData = [
            'labels' => $labels,
            'datasets' => [
                array(
                    'label' => 'Resultado',
                    'backgroundColor' => $colors,
                    'data' => $recording
                )
            ]
        ];
    }

}

The output for the $itemData is

{
   "labels":[
      "asdfas1",
      "fasdfsfs2",
      "asdfasf3"
   ],
   "datasets":{
      "labels":"Resultado",
      "backgroundColor":[ "#1E3260",  "#00B9FF", "#04FF00", "#FBB437", "#F7FF00",  "#D4D4D4",  "#00FF0C", "#000000", "#006E60",  "#FFFF00",  "#00F3FF", "#FF00FF", "#7A3F3F", "#D4FF00", "#FF9300", "#FF6161", "#8361FF", "#61C3FF", "#007EBD", "#00BABD", "#532400",  "#00DFA2", "#C89C8D",  "#53f545",  "#f5455d", "#3aab30", "#39678c", "#8c6339"
      ],
      "data":[ 5 ]
   }
}

I need it to be this instead

{
   "labels":[
      "asdfas1",
      "fasdfsfs2",
      "asdfasf3"
   ],
   "datasets":{
      "labels":"Resultado",
      "backgroundColor":[ "#1E3260",  "#00B9FF", "#04FF00", "#FBB437", "#F7FF00",  "#D4D4D4",  "#00FF0C", "#000000", "#006E60",  "#FFFF00",  "#00F3FF", "#FF00FF", "#7A3F3F", "#D4FF00", "#FF9300", "#FF6161", "#8361FF", "#61C3FF", "#007EBD", "#00BABD", "#532400",  "#00DFA2", "#C89C8D",  "#53f545",  "#f5455d", "#3aab30", "#39678c", "#8c6339"
      ],
      "data":[ 2, 2, 1 ]
   }
}

I feel like I'm so close but can't figure out how to fix it, it's adding all of them together instead of separating them by the option. How can I fix it?

0 likes
3 replies
eggplantSword's avatar

@jlrdw I'm still confused how should I change my code, I am doing 2 foreaches which is similar to the example you provided, or am I missing something?

eggplantSword's avatar
eggplantSword
OP
Best Answer
Level 9

This is the solution to my question, I was saving the $record to the collection outside of the foreach loop which is what caused the issue of saving the total and not the correct amount per label.

foreach ($item['surveyQuestionOption'] as $key => $option) {
    $labels[] = $option->option;
    foreach ($answer as $d) {
        if ($option->id == $d->answer) {
            $record++;
        }
    }
    $recording[] = $record;
    $record = 0;
}

Please or to participate in this conversation.