Auto detect number of same entry and do a rowspan according to the number?
i wanted to create a forloop which will create a table from the data obtained from the database.
the obtained result looks something like this.
id/cart_id/title/price/quantity
1 / 1 /book1/10.00/ 2
2 / 1 /book2/19.00/ 1
In the for loop its normal to create 2 tab开发者_如何转开发le row to hold these 2 results. However i want one of the to rowspan and show only cart_id "1" once.
this is my current code
<?php
for($i = 0; $i < count($history); $i++) {
$a = $history[$i]['cart_id'];
echo '<tr >';
if($history[$i]['cart_id'] == $history[$i]['cart_id']){
echo '<td rowspan="2">'.$a.'</td>';
}
echo '<td>'.$history[$i]['title'].'</td>';
echo '<td>'.$history[$i]['price'].'</td>';
echo '<td>'.$history[$i]['quantity'].'</td>';
echo '<td>'.$history[$i]['cart_id'].'</td>';
echo '</tr>';
}
?>
edit
original output:
[id:1][book1][19.90][2]
[id:1][book2][10.90][1]
what i wanted: The id row will rowspan according to the number of same ID.Thus showing ony 1 "id:1"
[ ][book1][19.90][2]
[id:1][book2][10.90][1]
How is it possible to achieve what i want?
You can achieve this with an extra for
loop:
<?php
$lastcart = FALSE ;
for($i = 0; $i < count($history); $i++) {
$a = $history[$i]['cart_id'];
echo '<tr >';
$rowspan = 0;
for(
$j=$i;
$history[$i]['cart_id'] !== $lastcart &&
$j < count($history) &&
$history[$j]['cart_id']==$history[$i]['cart_id'];
$j++
){
$rowspan++ ;
}
if($rowspan > 0){
$lastcart = $history[$i]['cart_id'] ;
echo '<td rowspan="{$rowspan}">'.$a.'</td>';
}
echo '<td>'.$history[$i]['title'].'</td>';
echo '<td>'.$history[$i]['price'].'</td>';
echo '<td>'.$history[$i]['quantity'].'</td>';
echo '<td>'.$history[$i]['cart_id'].'</td>';
echo '</tr>';
}
?>
精彩评论