2015-10-05 66 views
1

我從數據庫中排列如下:1.4.3日期在一個表填充缺少的日期,以便

$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] 

希望這是有道理的。

+0

似乎您自己找到解決方案,在日期爲空時添加虛擬值。 –

回答

0

我假設你有一個開始和結束年你想要顯示的聲明。然後,如果你用這個替換內循環,我認爲它應該工作:

$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>'; 
    } 
} 

這隻適用於索賠按年排序。請注意,我沒有測試過這些代碼。