php foreach来自每个项目添加tr

时间:2014-01-22 22:23:57

标签: php mysql

我有数据阵列产品

我尝试查看

<table>
<?php foreach($products as $object): ?>
    <tr>
        <th colspan="2" class="center"><?php echo $object->name;?></th>

        <?php if ($object->id%1 == 0):?>
            <tr>
                <th class="center">Count</th>
                <th class="center">Price</th>
            </tr>
        <?php endif; ?>


    </tr>
<?php endforeach;?>
</table>

但我想要这样的其他输出视图: enter image description here

我有数据库到

的区域数组

1 个答案:

答案 0 :(得分:2)

我真的不明白你的问题,但这是我对你认为的事情的回答

<?php

// IGNORE THIS IS JUST BUILDING PRODUCTS

$product = new stdclass();
$product->name = 'Product 1';
$product->id = 1;
$product->count = 3;
$product->price = 4;

$products[] = $product;

$product = new stdclass();
$product->name = 'Product 2';
$product->id = 2;
$product->count = 1;
$product->price = 7;

$products[] = $product;

$product = new stdclass();
$product->name = 'Product 3';
$product->id = 3;
$product->count = 5;
$product->price = 3;

$products[] = $product;

$region = new stdclass();
$region->name = 'Region 1';

$regions[] = $region;

$region = new stdclass();
$region->name = 'Region 2';

$regions[] = $region;
?>

<style>
table, tr, td, th
{
    border: 2px solid #000;
}

th 
{
    background: #ccc;
}

td
{
    width: 100px;
}

.center 
{
    text-align: center;
}
</style>

<table>
<tr>
<th class="center" rowspan="2" >Regions</th>
<?php foreach( $products as $product ): ?>
<th colspan="2" class="center"><?php echo $product->name; ?></th>
<?php endforeach; ?>
</tr>

<tr>
<?php foreach( $products as $product ): ?>
<th class="center">Count</th><th class="center">Price</th>
<?php endforeach; ?>
</tr>

<?php foreach( $regions as $region ): ?>
<tr>
<td><?php echo $region->name; ?></td>
<?php foreach( $products as $product ): ?>
<td><?php echo $product->count; ?></td><td><?php echo $product->price; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

这将导致 enter image description here