I have this query:
$this->set('grades', $this->Grade->Query("
SELECT AVG(grade),
sections.section_name
FROM grades,
sections
WHERE sections.id = grades.section_id
AND grades.user_id =".$id."
GROUP BY grades.section_id"));
And I use this to output the data:
<?php foreach($grades as $grade): ?>
<tr>
<td><?php echo $grade['Grade']['AVG(grade)']; ?></td>
</tr>
<?php endforeach;?>
But it gives me a “warning index Grade not found”. I suspect it got to do with the ['AVG(grade)'] because when I remove the AVG(grade) it outputs normal (without avg values obviously)
Is there anyone who can help?
EDIT
debug($grades) outputs:
Array
(
[0] => Array
(
[0] => Array
(
[avg_grade] => 4.75000
)
[sections] => Array
(
[section_name] => Nederlands
)
)
[1] => Array
(
[0] => Array
(
[avg_grade] => 6.50000
)
[sections] => Array
(
[section_name] => Engels
)
)
)
First, do
debug( $grades )to see where the average is stored in the array structure. You can also name it something else in the query, for exampleSELECT AVG( grade ) AS average.As a side note, you don’t need to use a raw query (perhaps a matter of preference, but I tend to avoid them if at all possible). You can do
In this case when you do
foreach( $grades as $grade )the averages will be in$grade[0]['average'].