我目前正面临着根据数组中名为category的项目将数组分组到html表中的问题。
我有以下代码:
foreach ($this->items as $item) {
$categories[] = $item->category;
}
<?php foreach ($categories as $category): ?>
<table class="table table-bordered">
<?php foreach ($this->items as $item) :?>
<tr>
<td></td>
<td><?php echo $item->description; ?></td>
<td><?php echo $item->price; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
但是我怎么告诉它,根据它的类别,它需要进入一个表或为该类别创建一个表?
每个单独类别的最终结果应如下所示:
添加说明
想想我修好了..我用过这段代码:
foreach( $this->items as $item ){
if( !isset( $zones[ $item->zone ] ) )
$zone_items[ $item->zone] = array();
$zone_items[ $item->zone ][] = $item;
$zones[$item->zone] = array(
'zone' => $item->zone,
'zone_description' => $item->zone_description,
'items' => $zone_items[$item->zone]
);
}
<?php foreach( $zones as $zone): ?>
<?php echo $zone['zone']; ?><br />
<?php echo $zone['zone_description']; ?>
<?php foreach( $zone['items'] as $items ) :?>
<?php echo $items->name; ?>
<?php echo $items->description; ?>
<?php echo $items->category; ?>
<?php endforeach; ?>
<?php endforeach; ?>
我获得了名称和描述,但没有任何项目..帮助非常感谢。
答案 0 :(得分:1)
这个怎么样?我没有测试它,所以原谅任何错误,但是,你明白了:)我的例子中的表格也很棘手,嗯......只需要一些摆弄就可以从这里得到它; P
$categories = array();
foreach( $this->items as $item )
{
if( !isset( $categories[ $item->category ] ) ) $categories[ $item->category] = array();
$categories[ $item->category ][] = $item;
}
<?php foreach( $categories as $category => $items ): ?>
<table class="table table-bordered">
<tr>
<td rowspan="<?php echo count( $items ); ?>"><?php echo $category; ?></td>
<?php foreach( $items as $item ) :?>
<td><?php echo $item->description; ?></td>
<td><?php echo $item->price; ?></td>
<?php endforeach; ?>
</tr>
</table>
<?php endforeach; ?>
要包含类别说明,您需要重新编写数组。现在,我不知道你的类别描述来自哪里,所以我只是告诉你数组和输出应该如何看待,并让你知道如何构建它;
<?php
$categories = array(
array(
'name' => 'Category Name',
'description' => 'This is the category description',
'items' => $itemsForThisCategory //you can still sort the items by category like I did above and then do "$itemsSortedByCategory[ 'Category Name' ]" here
),
array(
'name' => 'Another Category Name',
'description' => 'This is the description for another category',
'items' => $itemsForAnotherCategory
),
//etc... as many categories as you have
);
?>
然后输出看起来像这样;
<?php foreach( $categories as $category ): ?>
<table class="table table-bordered">
<tr>
<td rowspan="<?php echo count( $category['items'] ); ?>">
<?php echo $category['name']; ?><br />
<?php echo $category['description']; ?>
</td>
<?php foreach( $category['items'] as $item ) :?>
<td><?php echo $item->description; ?></td>
<td><?php echo $item->price; ?></td>
<?php endforeach; ?>
</tr>
</table>
<?php endforeach; ?>
答案 1 :(得分:0)
$categories = [];
foreach( $this->items as $item )
{
$categories[$item->category][] = $item;
}
现在你应该有一个关联的$categories
数组,每个索引都是一个类别,并包含该类别的项目。现在,您只需使用foreach遍历它,输出$category
索引,然后输出包含在其中的对象。