我的问题是我从数据库中获取了一个数组值,但是当我想使用foreach在页面上显示时,它什么也不显示。我找不到我的问题。在下面的代码中:
控制器:
$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;
视图:
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>
我回显$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
)
)
)
答案 0 :(得分:1)
假设您在视图中处于foreach的状态,看起来您在为键和值使用相同的变量,并且正在遍历数组数组。
只要$data['avg']
等于$avg
,这样的事情就应该起作用
<td>
<?php foreach ($avg as $value) { ?>
<?php echo $value[0]['average']; ?>
<br>
<br>
<?php } ?>
</td>
答案 1 :(得分:1)
您正在做的是为每个平均值创建一个数组,然后将其推入数据数组。
像下面一样直接将其推入数据数组
$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);
}
现在您可以像现在一样在foreach循环中使用它
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>