I have the correct data that I want to use in the view, but I want to slightly change it in the Controller, so it's easier to present in the view.
Each 'question' will always have 6 answers (score
). Each score
is an integer.
The calculation that I want to perform within each of the question's answers is:
So in the example below, within the answers array of 24 => array:1 [▼
:
- Get the score of index 1, and divided it by the score in index 0.
- Get the score of index 3, and divided it by the score of index 2.
- Get the score of index 5, and divided it by the score of index 4.
So at the end of the three iterations, there'll be 3 values within the answer. It will then move on to 25 => array:1 [▶]
and perform the same as above.
The slight problem is that the divisor could be 0, which would result in a division by 0 error. I have attempted to mitigate this with an if statement within the loop.
High level array ($groupedQuestionsAudit
) overview:
array:7 [▼
24 => array:1 [▼
"answers" => array:6 [▼
0 => ReAudit {#517 ▶}
1 => ReAudit {#518 ▶}
2 => ReAudit {#519 ▶}
3 => ReAudit {#520 ▶}
4 => ReAudit {#521 ▶}
5 => ReAudit {#522 ▶}
]
]
25 => array:1 [▶]
26 => array:1 [▶]
27 => array:1 [▶]
29 => array:1 [▶]
30 => array:1 [▶]
31 => array:1 [▶]
]
Section confirming score variable within array:
array:7 [▼
24 => array:1 [▼
"answers" => array:6 [▼
0 => ReAudit {#517 ▼
#original: array:9 [▼
"id" => 337
"score" => 8
"created_at" => null
"updated_at" => null
]
}
1 => ReAudit {#518 ▶}
Current iteration:
foreach ($groupedQuestionsAudit as $score) {
foreach ($score as $value) {
for ($i = 0; $i <= 3; $i++) {
for ($o = 1; $o <= 4; $o++) {
if ($value[$o]->score == 0) {
$answers['answers'][] = 0;
} else {
$answers['answers'][] = $value[$o]->score / $value[$i]->score;
}
}
}
}
}
My thought on the above was to loop through each of the questions and use an additional for loop that starts 1 index above the previous one. I can then perform the calculation of index 1's score / index 0's score
. I don't think that this works correctly though, as if I temporarily remove the division by 0 check, it returns 112 results (without being in their respective question array) like so:
array:1 [▼
"answers" => array:112 [▼
0 => 0
1 => 1.5
2 => 1
3 => 1.5
4 => 0
5 => 0
6 => 0
7 => 0
The error itself is:
ErrorException in Controller.php line 356: Division by zero which is on the line
$answers['answers'][] = $value[$o]->score / $value[$i]->score;
I'm unsure why I'm getting a division by 0, when I'm disregarding the calculation if the divisor is zero.
Many thanks.