Reputation: 139
My problem is I get an array value from my database but when I want to show on my page using foreach it show nothing. I can't findout my problem. In the below I give my code:
controller:
$subject_code = $this->student_model->subject_code($id);
$avg = array();
foreach($subject_code as $values) {
$array_values = $values['code'];
$avg[] = $this->student_model->average($id,$array_values);
}
$data['avg'] = $avg;
view:
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>
The output I get when I echo $data['avg']
:
Array
(
[0] => Array
(
[0] => Array
(
[average] => 77.666667
)
)
[1] => Array
(
[0] => Array
(
[average] => 74.333333
)
)
[2] => Array
(
[0] => Array
(
[average] => 89.333333
)
)
[3] => Array
(
[0] => Array
(
[average] => 88.666667
)
)
[4] => Array
(
[0] => Array
(
[average] => 39.666667
)
)
[5] => Array
(
[0] => Array
(
[average] => 37.666667
)
)
[6] => Array
(
[0] => Array
(
[average] => 43.333333
)
)
)
Upvotes: 0
Views: 1345
Reputation: 1876
what you are doing is creating an array for every average value and then pushing it in to the data array.
directly push it into the data array like following
$subject_code = $this->student_model->subject_code($id);
foreach($subject_code as $key=>$values) {
$array_values = $values['code'];
$data['avg'][$key] = $this->student_model->average($id,$array_values);
}
now you can use it in the foreach loop as you are already doing
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>
Upvotes: 1
Reputation: 26
Assuming you are on about foreach in your view, it looks like you are using the same variable for the key and value and you are looping over an array of arrays.
Something like this should work as long as $data['avg']
is equal to $avg
<td>
<?php foreach ($avg as $value) { ?>
<?php echo $value[0]['average']; ?>
<br>
<br>
<?php } ?>
</td>
Upvotes: 1