数据库中的数组如下所示:
$client[0]['Name'] = 'Foo';
$client[0]['Claim'][0]['year'] = 2013;
$client[0]['Claim'][1]['year'] = 2014;
$client[0]['Claim'][2]['year'] = 2015;
$client[1]['Name'] = 'Bar';
// no 2013!
$client[1]['Claim'][0]['year'] = 2014;
$client[1]['Claim'][1]['year'] = 2015;
// table headers are name, 2013, 2014, 2015...
foreach($client as $c) {
echo '<tr>';
echo '<td>' . $c['Client']['name'] . '</td>';
foreach($c['Claim'] as $claim) :
echo '<td>' . $claim['year'] . '</td>';
endforeach;
echo '</tr>';
}
除$client
缺失一年外,<td>
不平衡;导致我的表不正确。
我的目标是使每个$claim['Year']
与适当的表标题对齐。
我想我可以给每个数组添加空键并重新排序,但这似乎有点不必要,我想知道是否有更好的方法。
所以数组可能看起来像
这将是理想的:
$years[null, 2014, 2015]
而现在是
$years[2014,2015]
希望这是有意义的。
假设您希望显示索赔的开始年份和结束年份。然后,如果你用这个替换内部的for循环,我认为它应该可以工作:
$x = 0; //Variable to keep track of what claim we are on.
//Loop through the years.
for($i=$start; $i<=$stop; $i++) {
//If there is a claim for this year, echo it and move on to the next claim.
if($c['Claim'][$x]['year'] == $i) {
echo '<td>' . $c['Claim'][$x]['year'] . '</td>';
$x++;
}
//If not, just echo an empty table cell.
else {
echo '<td></td>';
}
}
这只适用于按年排序的索赔。请注意,我还没有测试代码。