【问题标题】:Outputting dates in to a table padding missing dates in order将日期输出到表格中,按顺序填充缺失的日期
【发布时间】:2015-10-05 13:40:19
【问题描述】:

我的数据库数组如下所示:

$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 缺少一年,然后&lt;td&gt; 不平衡;导致我的表格不正确。

我的目标是让每个$claim['Year'] 与适当的表格标题对齐。

我想我可以为每个数组添加空键并重新排序,但这似乎有点不必要,我想知道是否有更好的方法。

所以数组可能看起来

这将是理想的:

$years[null, 2014, 2015]

现在是

 $years[2014,2015]

希望这是有道理的。

【问题讨论】:

  • 似乎您自己找到了解决方案,当日期为空时添加虚拟值。

标签: php arrays date logic html-table


【解决方案1】:

我假设您有一个开始年份和一个结束年份来显示其声明。然后,如果你用这个替换内部 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>';
    }
}

仅当索赔按年份排序时才有效。请注意,我没有测试过代码。

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2019-07-20
    相关资源
    最近更新 更多