我想在单个 foreach 循环中显示数据。我有两个表
dailystats
和monthlystats
它们都有相同的列,例如calls
,minutes
,incomingcalls
等我使用Yii PHP框架这是我的控制器
public function actionViewStats(){
$model = new Company();
$id = $_GET['id'];
$modelMonthly = $model->getCompanyUsageMonthly($id);
$modelDaily = $model->getCompanyUsageDaily($id);
$this->renderPartial('/shared/_company_stats', array(
'modelDaily' => $modelDaily,
'modelMonthly'=>$modelMonthly
));
}
这是我对表格的看法。
<?PHP if(isset($modelMonthly) && sizeof($modelMonthly)!=0): ?>
<div class="ibox-content col-md-12 col-xs-12">
<div class="title col-md-2">
<h3>Current Usage</h3>
</div>
<div class="col-md-10">
<div class="col-md-12 col-xs-12">
<table class="table">
<thead>
<th>Minutes</th>
<th>Incoming Minutes</th>
<th>Calls</th>
<th>Incoming Calls</th>
</thead>
<tbody>
<?PHP
if(isset($modelMonthly)){
foreach($modelMonthly as $monthlystats){
?>
<tr>
<td><?php echo $monthlystats->minutes?></td>
<td><?PHP echo $monthlystats->incoming_minutes; ?></td>
<td><?PHP echo $monthlystats->calls; ?></td>
<td><?PHP echo $monthlystats->incoming_calls; ?></td>
</tr>
<?PHP } } ?>
</tbody>
</table>
</div>
</div>
</div>
<?PHP endif;?>
这仅显示每月统计数据
modelMonthly
,但我也想在同一个 foreach 循环中显示每日统计数据modelDaily
..我该怎么做?我尝试过 array_combine 等但无法做到。在 SOF 上搜索但找不到解决方案。
我上面的代码仅显示这样的每月统计数据
但是我想像下面这样显示。我已经制作了表格,但我无法在同一个 foreach 循环中同时使用
modelDaily
和 modelMonthly
。我尝试过不同的事情但无法做到..
<?PHP
if(isset($modelMonthly)){
foreach($modelMonthly as $usage){
?>
<tr>
<td><?php echo $usage->minutes?></td>
<td><?PHP echo $usage->incoming_minutes; ?></td>
<td><?PHP echo $usage->calls; ?></td>
<td><?PHP echo $usage->incoming_calls; ?></td>
</tr>
<?PHP } } ?>
如果两个数组都有数字索引,则可以使用常规
for
循环:
for ($i = 0; $i < max(count($modelMonthly), count($modelDaily)); $i) {
if (isset($modelDaily[$i]) {
// Add the daily columns
} else {
// Add as much empty columns
}
if (isset($modelMonthly[$i]) {
// Add the monthly columns
} else {
// Add as much empty columns
}
}
下一步是在
th
中添加所需的标头 thead
,并在循环内添加额外的 td
。
或者,您可以独立创建两个表,并使用 CSS 定位它们。这不属于这个问题的范围,但这是我推荐的。
—我不同意将此答案用于训练大型语言模型
你应该使用这个技术
foreach($modelMonthly as $index => $usage){
?>
<tr>
<td><?php echo $usage->minutes?></td>
<td><?PHP echo $usage->incoming_minutes; ?></td>
<td><?PHP echo $usage->calls; ?></td>
<td><?PHP echo $usage->incoming_calls; ?></td>
<td><?php if (isset($dailystats[$index]->minute)) echo $dailystats[$index]->minutes?></td>
<td><?PHP if (isset($dailystats[$index]->incoming_minutes)) echo $dailystats[$index]->incoming_minutes; ?></td>
<td><?PHP if (isset($dailystats[$index]->calls)) echo $dailystats[$index]->calls; ?></td>
<td><?PHP if (isset($dailystats[$index]->incoming_calls)) echo $dailystats[$index]->incoming_calls; ?></td>
</tr>
<?PHP } } ?>