【发布时间】:2018-08-03 03:02:39
【问题描述】:
我有以下代码。到目前为止,我还没有完全学会如何修改它以满足我的项目需求;但是,我正在慢慢学习此代码的不同元素。我以前从来没有做过这样的事情,所以这对我来说有点新鲜。
现在,代码从本例中的数据数组获取信息。实际上,它来自数据库;然而,这只是让它更容易使用。它遍历整个数组,收集完所有数据后,它构建表并根据数组中特定大小的条目数自动将“大小”列的行数设置为所需的行数。一旦检测到新的大小,它就会添加一个新的标题行并重新开始。
问题:
但是如果我也希望它计算另一列怎么办我需要修改什么才能使用自动行跨度来拥有多个列?
因此,不仅“尺寸”列会自动计算,“厚度”列也会单独计算。为了得到这样的东西......
----------------------------------------
name size thickness price
----------------------------------------
1 | | | $25 |
----- -------------
2 | 2x2 | | $27 |
------ ---------------
3 | | .160 | $30 |
--------------- ---------------
4 | 2x3 | | $40 |
---------------- ---------------
5 | 3x3 | | $55 |
-----------------------------------------
在上面的示例中,大小 (2x2) 和厚度 (.160) 都添加了行跨度,但它们会自动计算行跨度中所需的行数。
代码
$data = array(
array("name" => "item1", "size" => "2 x 2", "thickness" => ".020", "price" => "$25"),
array("name" => "item2", "size" => "2 x 2", "thickness" => ".025", "price" => "$28"),
array("name" => "item6", "size" => "2 x 2", "thickness" => ".080", "price" => "$50"),
array("name" => "item3", "size" => "2 x 2", "thickness" => ".030", "price" => "$30"),
array("name" => "item4", "size" => "2 x 2", "thickness" => ".040", "price" => "$40"),
array("name" => "item5", "size" => "3 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item6", "size" => "3 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item7", "size" => "3 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item8", "size" => "3 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item9", "size" => "4 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item10", "size" => "4 x 2", "thickness" => ".050", "price" => "$43"),
array("name" => "item11", "size" => "4 x 2", "thickness" => ".050", "price" => "$43"),
);
# Create storage array
$transfer = [];
# Loop $data
foreach($data as $row) {
# Make the size the key value
$transfer[$row['size']][] = $row;
}
# Now just loop over the first array which is the grouping
?>
<table>
<?php foreach($transfer as $block => $rows): ?>
<tr>
<th>Name</th>
<th>Size</th>
<th>Thickness</th>
<th>Price</th>
</tr>
<?php
# Set the default rowspan as empty
$rowspan = false;
# This indicates an easy way to note that you need a new header row
$start = true;
# Loop each rows now
foreach($rows as $row):
if(!empty($start)) {
# Assign rowspan
$rowspan = count($rows);
# This is the first row, so make sure the start is set false
# for subsequent rows
$start = false;
}
?>
<tr>
<td><?php echo $row['name'] ?></td>
<?php if(!empty($rowspan)): ?>
<td rowspan="<?php echo $rowspan; $rowspan = false; ?>"><?php echo $row['size'] ?></td>
<?php endif ?>
<td><?php echo $row['thickness'] ?></td>
<td><?php echo $row['price'] ?></td>
</tr>
<?php endforeach ?>
<?php endforeach ?>
</table>
【问题讨论】:
标签: php